如何在应用程序中指定自定义过滤器.yml 春季云网关

我有一个自定义网关过滤器MYGatewayFilter.java文件,现在我想使用此网关过滤器,并将我的路由写入应用程序。yml

 spring:
  cloud:
   gateway:
    routes:
      - id: login2_route
      uri: http://127.0.0.1:8083/login
      predicates:
       - Path: /login/
      filters:

如何为上述路由定义过滤器

自定义筛选器 MyGatewayFilter.java

public class MyGatewayFilter implements GatewayFilter {
    @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
      ServerHttpRequest request;
      if(request.getHeaders().get("x-mydata")!=null){
         request= exchange.getRequest().mutate().header("my-new-header",request.getHeaders().get("x-mydata").get(0)).build();
      }

      return chain.filter(exchange.mutate().request(request).build());
  }
}       

答案 1

与其实现 GatewayFilter,不如实现 GatewayFilterFactory。

并使其成为组件:

@Component
public class MyGatewayFilter implements GatewayFilterFactory {

然后,您可以通过路线中的豆名称来引用它。

filters:
- MyGatewayFilter

关于此的文档目前不是很好。我只能通过查看github上spring-cloud-gateway的源代码来解决这个问题。


答案 2

您需要实施GatewayFilterFactory

@Component
public class DemoGatewayFilter implements GatewayFilterFactory<DemoGatewayFilter.Config> {

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            System.out.println("gateway filter name "+config.getName());
            return chain.filter(exchange);
        };
    }

    @Override
    public Config newConfig() {
        return new Config("DemoGatewayFilter");
    }

    public static class Config {

        public Config(String name){
            this.name = name;
        }
        private String name;

        public String getName() {
            return name;
        }

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

和在 application.yml 文件中

 spring:
  application:
  cloud:
    gateway:
      routes:
      - id: MayApplication
        uri: http://myapplication:8080
        predicates:
        - Path=/apipath/to/filter/**
        filters:
          - DemoGatewayFilter

推荐