核心区别
详细对比
1. spring-cloud-gateway-server-webflux
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-server</artifactId>
</dependency>
<!-- 或者明确指定 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId> <!-- 默认使用 WebFlux -->
</dependency>特点:
✅ 默认实现(Spring Cloud Gateway 首选)
✅ 基于 Netty 服务器
✅ 支持响应式流(Reactive Streams)
✅ 更好的资源利用(内存、线程)
✅ 支持背压(Backpressure)
✅ 适合微服务网关(大量网络IO)
示例配置:
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route", r -> r.path("/get")
.uri("http://httpbin.org"))
.build();
}2. spring-cloud-gateway-server-webmvc
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-mvc</artifactId>
</dependency>特点:
✅ 基于 Servlet 3.1+ API
✅ 使用 Tomcat/Jetty/Undertow 等 Servlet 容器
✅ 同步阻塞模型
✅ 熟悉的 Spring MVC 编程模型
✅ 兼容传统 Spring 应用
示例配置:
@RestController
public class GatewayController {
@GetMapping("/api/**")
public ResponseEntity<?> proxy(@PathVariable String path,
HttpServletRequest request) {
// 传统的 Servlet API 处理
}
}技术架构差异
WebFlux 版本(响应式)
客户端请求 → Netty Event Loop → Reactive Handler → 响应式后端调用
↓ ↓ ↓
非阻塞处理 少量线程 Mono/Flux 流WebMVC 版本(传统)
客户端请求 → Servlet容器线程池 → Controller → 同步后端调用
↓ ↓ ↓
阻塞等待 线程切换 同步返回性能特征对比
选择建议
选择 WebFlux 版本当:
网关需要处理大量并发连接(1000+)
后端服务调用存在延迟(需要非阻塞)
系统需要更好的可伸缩性
想要采用响应式编程模型
需要处理流式数据(如SSE、WebSocket)
选择 WebMVC 版本当:
团队熟悉 Spring MVC
现有系统基于 Servlet 技术栈
网关逻辑简单,并发不高
需要与传统的 Spring 库集成
运维团队熟悉 Tomcat/Jetty
实际使用注意
混合使用问题:
不能在同一个应用中同时使用 WebFlux 和 WebMVC
选择后需要统一技术栈
Spring Boot 3 变化:
# Spring Boot 3 中,如果要使用 WebMVC 网关需要明确配置
spring:
main:
web-application-type: servlet依赖关系:
<!-- Gateway + WebFlux(默认) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Gateway + WebMVC(需明确) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway-mvc</artifactId>
</dependency>总结
WebFlux 是 Spring Cloud Gateway 的默认和推荐选择,特别适合作为 API 网关
WebMVC 主要为了兼容性,让熟悉 Spring MVC 的团队也能使用网关功能
对于新的网关项目,优先选择 WebFlux 版本
评论