SpringCloud gateway 除了具备路由的功能,也支持对请求的过滤,类似Zuul网关,也是通过过滤器实现的。
1.1 过滤器基础
1.1.1 过滤器生命周期
- Pre
Pre过滤器在请求被路由之前调用。可以通过pre过滤器实现身份认证
- Post
post过滤器是在路由到微服务后执行,可以用来给响应添加http header、收集统计信息和指标、将微服务响应返回给客户端
1.1.2 过滤器类型
- Gateway Filter
应用到单一或一组路由上
- Global Filter
应用到所有路由上
1.2 局部过滤器
序号 |
局部过滤器名称 |
1 |
AddRequestHeader GatewayFilter |
2 |
AddRequestParameter GatewayFilter |
3 |
AddResponseHeader GatewayFilter |
4 |
DedupeResponseHeader |
5 |
Hystrix |
6 |
Spring Cloud CircuitBreaker GatewayFilter |
7 |
FallbackHeaders GatewayFilter Factory |
8 |
MapRequestHeader GatewayFilter |
9 |
PrefixPath GatewayFilter |
10 |
PreserveHostHeader GatewayFilter |
11 |
RequestRateLimiter GatewayFilter |
12 |
RedirectTo GatewayFilter |
13 |
RemoveRequestHeader GatewayFilter |
14 |
RemoveResponseHeader GatewayFilter |
15 |
RemoveRequestParameter GatewayFilter |
16 |
RewritePath GatewayFilter |
17 |
RewriteLocationResponseHeader GatewayFilter |
18 |
RewriteResponseHeader GatewayFilter |
19 |
SaveSession GatewayFilter |
20 |
SecureHeaders GatewayFilter |
21 |
SetPath GatewayFilter |
22 |
SetRequestHeader GatewayFilter |
23 |
SetResponseHeader GatewayFilter |
24 |
SetStatus GatewayFilter |
25 |
StripPrefix GatewayFilter |
26 |
Retry GatewayFilter |
27 |
RequestSize GatewayFilter |
28 |
Modify a Request Body GatewayFilter |
29 |
Modify a Response Body GatewayFilter |
30 |
Default Filters |
1.3 全局过滤器
序号 |
全局过滤器名称 |
1 |
Forward Routing Filter |
2 |
The LoadBalancerClient Filter |
3 |
The ReactiveLoadBalancerClientFilter |
4 |
The Netty Routing Filter |
5 |
The Netty Write Response Filter |
6 |
The RouteToRequestUrl Filter |
7 |
The Websocket Routing Filter |
8 |
The Websocket Routing Filter |
9 |
The Gateway Metrics Filter |
1.4 自定义过滤器
-
创建自定义过滤器
com.xyz.gateway.filters.MyFilter
@Component
@Log4j2
public class MyFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("自定义全局过滤器-MyFilter");
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
复制代码
1.5 权限认证
- 修改MyFilter,判断请求参数中是否包含access-token,若包含继续处理,若不包含则返回
@Component
@Log4j2
public class MyFilter implements GlobalFilter, Ordered {
/**
* 认证鉴权:判断请求参数中是否包含access-token,若包含继续处理,若不包含直接返回
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("自定义全局过滤器-MyFilter");
String token = exchange.getRequest().getQueryParams().getFirst("access-token");
if ( token == null) {
log.info("没有登录");
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
复制代码
-
测试,请求
http://localhost:6101/product/provider/list?access-token=100
返回成功;
请求 http://localhost:6101/product/provider/list
返回未登录
原文
https://juejin.im/post/5e9fe442f265da47c4323051