为Spring Cloud Gateway加上全局过滤器,并使用其内部自带的令牌桶算法实现(Redis)来进行限流
既然是一个网关。那么全局过滤器肯定是少不了的一个存在。像是鉴权、认证啥的不可能每个服务都做一次,一般都是在网关处就搞定了。
Zuul他就有很强大的过滤器体系来给人使用。
Gateway当然也不会差这么点东西。
对于SpringCloud体系来说,一切的实现都是那么的简单。那么废话不多说,直接开始写起来。
Gateway内部有一个接口 名为GlobalFilter,这个就是Gateway的全局过滤器接口,只要在应用中实现此接口后注册为Spring的Bean,背后就会帮你将这个实现注册到全局过滤器链条里边去。
我这里就简单的写了个模拟鉴权的过滤器实现:
1
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
38
39
40@Component
publicclassAuthFilterimplementsGlobalFilter,Ordered{
@Override
publicMonofilter(ServerWebExchangeexchange,GatewayFilterChainchain){
Stringtoken=exchange.getRequest().getHeaders().getFirst("Authorization");
//不为空则通过
if(!StringUtils.isEmpty(token))returnchain.filter(exchange);
ServerHttpResponseresponse=exchange.getResponse();
// 封装错误信息
MapresponseData=Maps.newHashMapWithExpectedSize(3);
responseData.put("code",HttpStatus.UNAUTHORIZED.value());
responseData.put("message","Token is empty");
responseData.put("cause","Tok