摘要:无。
环境
Windows 10 企业版 LTSC 21H2
Java 1.8
Maven 3.6.3
Spring 5.3.31
Spring Boot 2.7.18
Spring Cloud 2021.0.5
Spring Cloud Gateway 3.1.4
1 概述
1.1 分类
过滤器分为两类,二者的作用范围不同:
- GatewayFilter:作用于单条路由,只对配置了该过滤器的路由生效。
- GlobalFilter:作用于所有路由,无需在路由上单独配置,对所有请求生效。
1.2 配置语法
过滤器在路由的filters节点下配置,一条路由可以配置多个过滤器,多个过滤器按顺序执行。
1.3 执行阶段
过滤器分为两个执行阶段:
- pre阶段:在请求被代理转发之前执行,可用于修改请求头、校验参数、鉴权等。
- post阶段:在收到下游响应之后执行,可用于修改响应头、记录耗时、埋点等。
同一条路由上的多个过滤器按顺序执行:
- 请求正向穿过所有过滤器的
pre阶段到达下游。
- 响应逆向穿过所有过滤器的
post阶段返回客户端。
2 常见过滤器
2.1 请求头和响应头
AddRequestHeader过滤器在转发前为请求追加请求头:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - AddRequestHeader=X-Request-Version, 1.0.0
|
下游服务可从请求头中读取X-Request-Version识别请求来源。
AddResponseHeader过滤器在响应返回前为响应追加响应头:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - AddResponseHeader=X-Response-Version, 1.0.0
|
客户端可从响应头中拿到X-Response-Version识别响应来源。
SetRequestHeader过滤器会覆盖同名请求头的值:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - SetRequestHeader=X-Request-Version, 2.0.0
|
SetResponseHeader过滤器会覆盖同名响应头的值:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - SetResponseHeader=X-Response-Version, 2.0.0
|
RemoveRequestHeader过滤器用于删除指定请求头:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - RemoveRequestHeader=X-Request-Version
|
RemoveResponseHeader过滤器用于删除指定响应头:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - RemoveResponseHeader=X-Response-Version
|
当网关和下游服务都设置了同名响应头时,响应中会出现重复的头。DedupeResponseHeader过滤器用于对指定响应头去重,支持指定保留策略:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_FIRST
|
保留策略:
- RETAIN_FIRST:保留第一个值,常用于解决跨域响应头重复的问题。
- RETAIN_LAST:保留最后一个值。
- RETAIN_UNIQUE:保留唯一值。
2.2 请求参数与响应状态
2.2.1 AddRequestParameter
AddRequestParameter在转发前为请求追加一个查询参数:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - AddRequestParameter=version, 1.0.0
|
下游收到的请求会带上version=1.0.0这一查询参数。
2.2.2 SetStatus
SetStatus强制把返回给客户端的响应状态码设置为指定值,常用于统一某些场景下的响应状态:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - SetStatus=200
|
无论下游返回什么状态码,网关最终都会以200响应客户端。
2.3 路径
2.3.1 StripPrefix
StripPrefix在转发前去掉请求路径开头指定数量的路径段,参数为要去除的段数:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/api/demo/** filters: - StripPrefix=1
|
客户端访问/api/demo/hello,网关去掉第一段/api后,实际转发给下游的路径为/demo/hello。
2.3.2 PrefixPath
PrefixPath在转发前为请求路径追加一个前缀:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - PrefixPath=/api
|
客户端访问/demo/hello,网关追加前缀/api后,实际转发给下游的路径为/api/demo/hello。
2.3.3 RewritePath
RewritePath使用正则表达式重写请求路径,是最灵活的路径改写方式,第二个参数中的$符号用于引用正则分组:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/api/demo/** filters: - RewritePath=/api/(?<segment>.*), /$\{segment}
|
重写目标里的$必须写成$\进行转义,即将${segment}使用$\{segment}代替,否则会被当作占位符解析而导致启动报错。
2.4 重试
2.4.1 Retry
Retry过滤器在下游调用失败或返回指定状态码时自动重试,可配置重试次数、触发重试的状态码和方法:
application.yml1 2 3 4 5 6 7 8 9 10 11 12 13 14
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - name: Retry args: retries: 3 series: SERVER_ERROR methods: GET
|
上面的配置表示当GET请求返回SERVER_ERROR(500)时最多重试3次。需要注意重试应只对幂等的方法开启,对POST等非幂等方法重试可能造成重复提交。
3 自定义过滤器
3.1 普通过滤器
实现记录请求处理耗时的过滤器:
java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| @Component public class CostTimeGatewayFilterFactory extends AbstractGatewayFilterFactory<CostTimeGatewayFilterFactory.Config> { public CostTimeGatewayFilterFactory() { super(Config.class); }
@Override public List<String> shortcutFieldOrder() { return Collections.singletonList("prefix"); }
@Override public GatewayFilter apply(Config config) { return (exchange, chain) -> { String prefix = config.getPrefix(); long start = System.currentTimeMillis(); return chain.filter(exchange).then(Mono.fromRunnable(() -> { long cost = System.currentTimeMillis() - start; System.out.println("请求处理完成:" + prefix + ",耗时:" + cost + "ms"); })); }; }
public static class Config { private String prefix;
public String getPrefix() { return prefix; }
public void setPrefix(String prefix) { this.prefix = prefix; } } }
|
在路由中使用:
application.yml1 2 3 4 5 6 7 8 9 10
| spring: cloud: gateway: routes: - id: filter-route uri: http://127.0.0.1:8080 predicates: - Path=/demo/** filters: - CostTime=demo
|
3.2 全局过滤器
实现统一鉴权的全局过滤器:
java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @Component @Order(0) public class AuthGlobalFilter implements GlobalFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String token = exchange.getRequest().getHeaders().getFirst("Authorization"); if (token == null || token.isEmpty()) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); response.getHeaders().setContentType(MediaType.APPLICATION_JSON); byte[] body = "{\"code\":401,\"msg\":\"未授权\"}".getBytes(StandardCharsets.UTF_8); return response.writeWith(Mono.just(response.bufferFactory().wrap(body))); } return chain.filter(exchange); } }
|
使用@Order注解指定顺序,数值越小越先执行。
条