自定义Spring Cloud Gateway过滤器工厂

SpringCloud视频教程:

https://ke.qq.com/course/2805647?tuin=a3e3fb1&from_uin=171851697&from=1000201007

个人博客纯净版

http://www.51ufo.cn/%E5%BE%AE%E6%9C%8D%E5%8A%A1/%E5%88%86%E5%B8%83%E5%BC%8F/2020/07/11/SpringCloud%E5%85%A5%E9%97%A820-%E8%87%AA%E5%AE%9A%E4%B9%89Spring-Cloud-Gateway%E8%BF%87%E6%BB%A4%E5%99%A8%E5%B7%A5%E5%8E%82.html

 

自定义 Spring Cloud Gateway 过滤器工厂需要继承 AbstractGatewayFilterFactory 类,重写 apply 方法的逻辑。命名需要以 GatewayFilterFactory 结尾,比如 AccessAuthGatewayFilterFactory,那么在使用的时候 AccessAuth就是这个过滤器工厂的名称。

自定义过滤器工厂代码如下所示。

@Slf4j
@Component
public class AccessAuthGatewayFilterFactory extends AbstractGatewayFilterFactory {

    public static final String WARNING_MSG = "访问未授权";

    public AccessAuthGatewayFilterFactory(){
        super(AccessAuthGatewayFilterFactory.Config.class);
        log.info("Loaded GatewayFilterFactory [AccessAuth]");
    }
@Override
public List shortcutFieldOrder() {
return Arrays.asList("name");
} 

    @Override
    public GatewayFilter apply(Config config) {

        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();
            if(config.name.equals("zhangsan")) {
                return chain.filter(exchange.mutate().request(request).build());
            } else {

                byte[] bits = WARNING_MSG.getBytes(StandardCharsets.UTF_8);
                DataBuffer buffer = response.bufferFactory().wrap(bits);
                //指定编码,否则在浏览器中会中文乱码
                response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
                return response.writeWith(Mono.just(buffer));
            }
        };

    }

    public static class Config {

        private String name;

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }
}

修改service-gateway服务application.yml配置文件的路由配置,如下:

spring:
  cloud:
    gateway:
      routes:
      - id: hello
        predicates:   #断言
        - Path=/hello
        uri: http://localhost:8080  #目标服务地址
        filters:
        - AccessAuth=lisi

启动服务,在浏览器访问在浏览器访问http://localhost/hello?name=xiaoming,返回如下:

访问未授权

若将service-gateway服务application.yml配置文件的路由配置修改,如下:

spring:
  cloud:
    gateway:
      routes:
      - id: hello
        predicates:   #断言
        - Path=/hello
        uri: http://localhost:8080  #目标服务地址
        filters:
        - AccessAuth=zhangsan

重新启动服务,从浏览器再次访问http://localhost/hello?name=xiaoming,返回如下:

hello, xiaoming, 我是服务提供者:端口为:8080

本文代码git地址 https://gitee.com/xmingtx/springcloud-lesson.git

你可能感兴趣的:(过滤器,gateway,spring,cloud,springBoot)