java 如何在application.yml Spring Cloud Gateway中指定自定义过滤器

ny6fqffe  于 2023-02-28  发布在  Java
关注(0)|答案(3)|浏览(118)

我有一个自定义网关过滤器MYGatewayFilter.java文件,现在我想将此网关过滤器与我的路径一起使用,路径写入application.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());
  }
}
bvpmtnay

bvpmtnay1#

您应该实现GatewayFilterFactory,而不是实现网关过滤器
并使其成为组件:

@Component
public class MyGatewayFilter implements GatewayFilterFactory {

然后可以通过路由中的bean名称引用它。

filters:
- MyGatewayFilter

目前关于这方面的文档还不是很好,我只能通过查看github上spring-cloud-gateway的源代码来了解这一点

ctzwtxfj

ctzwtxfj2#

您需要实现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;
        }
    }
}

和应用程序.yml文件中

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

0yg35tkg3#

我认为Spring Cloud Gateway 2.2.1有一些变化。
我指的是SaveSessionGatewayFilterFactory.java

@Component
public class DemoGatewayFilter extends AbstractGatewayFilterFactory {

    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            return chain.filter(exchange);
        };
/*
it works too
       return new GatewayFilter() {
           @Override
           public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
               return chain.filter(exchange);
           }
       }
*/
    }

}

和应用程序.yml文件中

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

相关问题