内置过滤器
1 AddRequestHeader GatewayFilter Factory 添加请求头
2 AddRequestParameter GatewayFilter Factory
3 AddResponseHeader GatewayFilter Factory
4 DedupeResponseHeader GatewayFilter Factory
5 Hystrix GatewayFilter Factory
6 FallbackHeaders GatewayFilter Factory
7 PrefixPath GatewayFilter Factory
8 PreserveHostHeader GatewayFilter Factory
9 RequestRateLimiter GatewayFilter Factory
10 RedirectTo GatewayFilter Factory
11 RemoveHopByHopHeadersFilter GatewayFilter Factory
12 RemoveRequestHeader GatewayFilter Factory
13 RemoveResponseHeader GatewayFilter Factory
14 RewritePath GatewayFilter Factory
15 RewriteResponseHeader GatewayFilter Factory
16 SaveSession GatewayFilter Factory
17 SecureHeaders GatewayFilter Factory
18 SetPath GatewayFilter Factory
19 SetResponseHeader GatewayFilter Factory
20 SetStatus GatewayFilter Factory
21 StripPrefix GatewayFilter Factory
22 Retry GatewayFilter Factory
23 RequestSize GatewayFilter Factory
24 Modify Request Body GatewayFilter Factory
25 Modify Response Body GatewayFilter Factory 26 Default Filters
使用内置过滤器
下图controller会输出bar!!!
自定义过滤器
命名规范:过滤器工厂的类名必须以GatewayFilterFactory为后缀
package com.qf.predicates;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* <p>title: com.wfx.filters</p>
* author zhuximing
* description:
*/
@Component
public class CalServiceTimeGatewayFilterFactory extends AbstractGatewayFilterFactory<MyConfig> {
public CalServiceTimeGatewayFilterFactory() {
super(MyConfig.class);
}
@Override
public GatewayFilter apply(MyConfig config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//前处理
long startTime = System.currentTimeMillis();
System.out.println("name:"+config.getKey());
System.out.println("value:"+config.getValue());
// return chain.filter(exchange);//放行
return chain.filter(exchange).then(
//后置处理
Mono.fromRunnable(()->{
System.out.println("post come in");
//获取系统当前时间戳为endTime
long entTime = System.currentTimeMillis();
System.out.println("time="+(entTime-startTime));
}));
}
};
}
//默认不用改
@Override
public ShortcutType shortcutType() {
return ShortcutType.DEFAULT;
}
}
server:
#gateway的端口
port: 8040
spring:
application:
name: cloud-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: pro #服务发布到指定的namespace,默认是public
group: my-group #服务发布到指定的group,默认值是DEFAULT_GROUP
gateway:
routes:
- id: cloud-goods
uri: lb://cloud-goods/
predicates:
- Path=/goods/**
- After=2021-08-23T15:51:15.200+08:00[Asia/Shanghai]
- Cookie=age,18
- MyHeader=name,jack
filters:
- AddRequestHeader=token,123
- CalServiceTime=a,b
- id: baidu
uri: http://www.baidu.com
predicates:
- Path=/** #http://localhost:8040/a=》http://www.baidu.com/a
全局过滤器
Spring Cloud Gateway内置的全局过滤器。包括:
1 Combined Global Filter and GatewayFilter Ordering
2 Forward Routing Filter
3 LoadBalancerClient Filter
4 Netty Routing Filter
5 Netty Write Response Filter
6 RouteToRequestUrl Filter
7 Websocket Routing Filter
8 Gateway Metrics Filter
9 Marking An Exchange As Routed
自定义全局过滤器
下图可以判断是否登录
package com.qf.filters;
import cn.hutool.json.JSONUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
/**
* <p>title: com.qf.filters</p>
* <p>Company: wendao</p>
* author zhuximing
* date 2021/8/23
* description:
*/
@Component
public class AuthFilter implements GlobalFilter, Ordered {
//针对所有的路由进行过滤
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//过滤器的前处理
ServerHttpRequest request = exchange.getRequest();
ServerHttpResponse response = exchange.getResponse();
String token = request.getHeaders().getFirst("token");
if(StringUtils.isEmpty(token)){
Map res = new HashMap(){{
put("msg", "没有登录!!");
}};
return response(response,res);
}else{
if(!"123".equals(token)){
Map res = new HashMap(){{
put("msg", "令牌无效!!");
}};
return response(response,res);
}else{
return chain.filter(exchange); //放行
}
}
}
private Mono<Void> response(ServerHttpResponse response,Object msg){
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
String resJson = JSONUtil.toJsonPrettyStr(msg);
DataBuffer dataBuffer = response.bufferFactory().wrap(resJson.getBytes());
return response.writeWith(Flux.just(dataBuffer));//响应json数据
}
//数字越小越先执行
@Override
public int getOrder() {
return 0;
}
public Mono<Void> response(ServerHttpResponse response,Object msg){
response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
String resJson = JSONUtil.toJsonPrettyStr(msg);
DataBuffer dataBuffer = response.bufferFactory().wrap(resJson.getBytes());
return response.writeWith(Flux.just(dataBuffer));//响应json数据
}
}