H__D  

Gateway Filter介绍

  Filter,在“pre”类型的过滤器可以做参数校验、权限校验、流量监控、日志输出、协议转换等,在“post”类型的过滤器中可以做响应内容、响应头的修改,日志的输出、流量监控等,有非常重要的作用

  Filter除了分为“pre”和“post”两种方式的Filter外,在Spring Cloud Gateway中,Filter从作用范围可分为另外两种,一种是针对于单个路由的Gateway Filter,它在配置文件中的写法同predict类似;另外一种是针对于所有路由的Global Gateway Filer。现在从作用范围划分的维度来讲解这两种Filer。

Gateway Filter的使用

1、单个路由的Gateway Filter用法

  参考官网:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.2.RELEASE/reference/html/#gatewayfilter-factories

2、Global Gateway Filer用法

  当请求与路由匹配时,过滤Web处理程序会将的所有实例GlobalFilter和所有特定GatewayFilter于路由的实例添加到过滤器链中。该组合的过滤器链按org.springframework.core.Ordered接口排序,您可以通过实现该getOrder()方法进行设置。

  由于Spring Cloud Gateway区分了执行过滤器逻辑的“前”阶段和“后”阶段,因此优先级最高的过滤器是“前”阶段的第一个,而“后”阶段的最后一个。

  演示项目使用【SpringCloud】Gateway路由配置(十七)节的代码示例

  1)在springcloud-gateway-gateway9527网关模块中,新建Filter实现接口 GlobalFilter, Ordered 

 1 @Component
 2 @Slf4j
 3 public class MyLogGateWayFilter implements GlobalFilter, Ordered {
 4     @Override
 5     public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
 6         log.info("=========Come in MyLogGateWayFilter: " + new Date() + "==========");
 7         String uname = exchange.getRequest().getQueryParams().getFirst("uname");
 8         if(uname == null) {
 9             log.info("=========用户名为null,非法用户========");
10             exchange.getResponse().setComplete();
11         }
12         // 成功
13         return chain.filter(exchange);
14     }
15 
16     @Override
17     public int getOrder() {
18         return 0;
19     }
20 }

  2)测试

    a、启动项目

    b、访问地址:http://localhost:9527/payment/get/1

    访问出错,日志记录打印非法用户

    c、访问地址:http://localhost:9527/payment/get/1?uname=1

    正常访问:

    

  

posted on 2020-04-21 01:56  H__D  阅读(2975)  评论(0编辑  收藏  举报