Spring Cloud Gateway 基础
约 497 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Spring Cloud › 网关
Spring Cloud Gateway 是基于 WebFlux 的 API 网关,提供路由、过滤、限流等功能。
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>注意:Gateway 基于 WebFlux,不能引入
spring-boot-starter-web,否则冲突。
路由配置
spring:
application:
name: gateway
cloud:
gateway:
routes:
- id: user-service # 路由 ID
uri: lb://user-service # lb:// 表示从 Nacos 负载均衡
predicates:
- Path=/api/users/** # 路径匹配
filters:
- StripPrefix=1 # 去掉第一级路径 /api
- id: product-service
uri: lb://product-service
predicates:
- Path=/api/products/**
filters:
- StripPrefix=1
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/orders/**
filters:
- StripPrefix=1用户请求 GET /api/users/100 → Gateway → lb://user-service/users/100。
Java 路由配置
@Configuration
public class GatewayRoutes {
@Bean
public RouteLocator customRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route("user-service", r -> r
.path("/api/users/**")
.filters(f -> f.stripPrefix(1))
.uri("lb://user-service"))
.route("product-service", r -> r
.path("/api/products/**")
.filters(f -> f.stripPrefix(1))
.uri("lb://product-service"))
.route("order-service", r -> r
.path("/api/orders/**")
.filters(f -> f.stripPrefix(1))
.uri("lb://order-service"))
.build();
}
}路由断言工厂
spring:
cloud:
gateway:
routes:
- id: api
uri: lb://backend
predicates:
- Path=/api/** # 路径匹配
- Method=GET,POST # HTTP 方法
- Header=X-Request-Type, \d+ # 请求头正则
- Query=token, .+ # 查询参数存在
- Cookie=session, [A-Z]+ # Cookie 匹配
- Host=**.example.com # 域名匹配
- RemoteAddr=192.168.1.1/24 # IP 限制
- Weight=group1, 50 # 权重路由(灰度发布)常用过滤器
filters:
- StripPrefix=1 # 去掉路径前缀
- PrefixPath=/api # 添加路径前缀
- AddRequestHeader=X-Custom, value # 添加请求头
- AddResponseHeader=X-Source, gateway
- RewritePath=/old/(?<seg>.*), /new/$\{seg} # 路径重写
- SetPath=/new/{segment} # 设置路径
- RedirectTo=301, https://new.example.com # 重定向
- Retry=3 # 重试启动验证
# 测试
curl http://localhost:8080/api/users/1 # → gateway → user-service/users/1
curl http://localhost:8080/api/products/1 # → gateway → product-service/products/1小结
- Gateway 基于 WebFlux(不能引入
spring-boot-starter-web)。 - 路由配置
uri: lb://service-name从 Nacos 发现并负载均衡。 - 断言工厂:
Path、Method、Header、Query、Cookie、Host、Weight。 - 过滤器:
StripPrefix、RewritePath、AddRequestHeader等。 - 支持 YAML 和 Java DSL 两种路由定义方式。
上一节:Feign 配置与拦截器 下一节:Gateway 过滤器与动态路由
