SpringCloud-Gateway
基本使用
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
路由配置
- 基于URL配置
server:
port: 9527
spring:
cloud:
gateway:
routes:
- id: PAYMENT-SERVICE-1
uri: http://localhost:8001
predicates:
- Path=/provider/user/findById/**
- id: PAYMENT-SERVICE-2
uri: http://localhost:8001
predicates:
- Path=/provider/user/discover/**
各字段含义如下:
id:自定义的路由ID,保持唯一
uri:目标服务地址
predicates:路由条件,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。
上面这段配置的意思是,配置了一个 id 为 PAYMENT-SERVICE-1 的URI代理规则,路由的规则为:
当访问地址 http://localhost:9527/provider/user/findById/1时,
会路由到地址http://localhost:8001/provider/user/findById/1
也可以直接使用注册中心的服务名
spring:
cloud:
gateway:
discovery:
locator:
enabled: true # 从注册中心动态创建路由
routes:
- id: PAYMENT-SERVICE
- #uri: http://localhost:8001
- uri: lb://PAYMENT-SERVICE
predicates:
- Path=/provider/user/findById/**
当访问地址 http://localhost:9527/provider/user/findById/1时,
会路由到地址http://PAYMENT-SERVICE/provider/user/findById/1
- 基于代码配置
@Bean
public RouteLocator myRoutes(RouteLocatorBuilder builder) {
// return builder.routes().route("routeId1", p -> p.path("/provider/user/**").uri("http://localhost:8001")).build();
return builder.routes().route( p -> p.path("/cnblog").uri("https://www.cnblogs.com/LooYang")).build();
}
当访问地址 http://localhost:9527/cnblog时,
会路由到地址https://www.cnblogs.com/LooYang
Gateway核心概念
路由
路由是构建网关的基本模块,它由ID,目标URI,一系列的断言和过滤器组成,如果断言为true则匹配该路由
spring.cloud.gateway.routes配置中以数组的形式存在
断言
参考的是java8的java.util.function.Predicate开发人员可以匹配HTTP请求中的所有内容(例如请求头或请求参数),如果请求与断言相匹配则进行路由
spring.cloud.gateway.routes[0].predicates[0]中,除了path还有其他的参数可以配置,参考官网文档gateway-request-predicates-factories
| 断言类型 | 描述 | 配置示例 |
|---|---|---|
| Path | 匹配请求路径(支持 Ant 风格通配符,如 *和 {segment}) |
- Path=/user/** - Path=/items/{id} |
| Method | 匹配 HTTP 请求方法(GET/POST/PUT/DELETE 等) | - Method=GET - Method=POST,PUT |
| Header | 匹配请求头名称及值(支持正则表达式) | - Header=X-Request-Id, \d+ - Header=User-Agent, .*Chrome.* |
| Query | 匹配 URL 查询参数(名称和值,支持正则) | - Query=showDetails - Query=category, electronics |
| Cookie | 匹配 Cookie 名称及值(支持正则) | - Cookie=session, [a-zA-Z0-9]+ |
| Host | 匹配请求 Host 头(支持通配符,如 *.example.com) |
- Host=**.example.com |
| RemoteAddr | 匹配客户端 IP 地址或 CIDR 地址段 | - RemoteAddr=192.168.1.1/24 |
| After | 匹配请求时间晚于指定时间(ISO8601 格式) | - After=2025-08-01T00:00:00+08:00[Asia/Shanghai] |
| Before | 匹配请求时间早于指定时间 | - Before=2025-08-31T23:59:59+08:00[Asia/Shanghai] |
| Between | 匹配请求时间在指定时间段内 | - Between=2025-08-01T00:00:00+08:00,2025-08-31T23:59:59+08:00 |
| Weight | 按权重分配流量(需配合 group参数) |
- Weight=group1, 8 - Weight=group1, 2 |
过滤器
指的是Spring框架中GatewayFilter的实例,使用过滤器,可以在请求被路由前或者之后对请求进行修改。
参考官方文档 gatewayfilter-factories
使用方式
spring:
cloud:
gateway:
routes:
- id: setrequestheader_route
uri: https://example.org
filters:
- SetRequestHeader=X-Request-Red, Blue
自定义过滤器
可以定义全局过滤器或者局部路由器
全局路由器对所有路由生效,一般用于统计用时等
局部路由器对指定路由生效
定义全局过滤器
@Slf4j
@Component
public class MyLogFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("******GlobalFilter 我来也****{}", new Date());
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
定义局部过滤器
创建过滤器配置类用于接收参数
@Data
public class CustomFilterConfig {
private String headerName;
private String headerValue;
}
实现过滤工厂
@Component
public class CustomHeaderFilterFactory extends AbstractGatewayFilterFactory<CustomFilterConfig> {
// 必须调用父类构造器
public CustomHeaderFilterFactory() {
super(CustomFilterConfig.class);
}
@Override
public GatewayFilter apply(CustomFilterConfig config) {
return (exchange, chain) -> {
// 1. 修改请求:添加自定义请求头
ServerHttpRequest modifiedRequest = exchange.getRequest()
.mutate()
.header(config.getHeaderName(), config.getHeaderValue())
.build();
// 2. 替换请求并继续过滤器链
return chain.filter(
exchange.mutate().request(modifiedRequest).build()
);
};
}
}
使用方式1,通过配置文件
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
# 使用自定义过滤器(自动识别前缀"CustomHeader")
- name: CustomHeader # 规则: 类名去掉"GatewayFilterFactory"后缀
args:
headerName: "X-Custom-Header"
headerValue: "HelloFromGateway"
使用方式2,通过Java DSL配置
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("auth-route", r -> r.path("/api/auth/**")
.filters(f -> f
.filter(new CustomHeaderFilterFactory()
.apply(config -> {
config.setHeaderName("X-Auth-Source");
config.setHeaderValue("Gateway");
})
)
)
.uri("lb://auth-service")
)
.build();
}

浙公网安备 33010602011771号