简体   繁体   English

如何在 Spring 云网关中添加特定于路由的自定义过滤器

[英]How to add a custom filter specific to a route in Spring Cloud Gateway

So I am new to spring cloud gateway and have just started playing around with it.所以我是 spring 云网关的新手,刚刚开始使用它。 I was going through the documentation and stumbled upon how to create a custom filter.我正在浏览文档并偶然发现如何创建自定义过滤器。

https://cloud.spring.io/spring-cloud-gateway/reference/html/#developer-guide

So this is my code for creating a custom filter -所以这是我创建自定义过滤器的代码 -

       @Component
      public class CustomPreFilterFactory extends AbstractGatewayFilterFactory<CustomPreFilterFactory.Config> {


      public static class Config {
        //Put the configuration properties for your filter here
      }

     @Override
     public GatewayFilter apply(Config config) {

       return (exchange,chain) ->{
        ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
        System.out.println("Request came in custom pre filter");
        return chain.filter(exchange.mutate().request(builder.build()).build());
      };
    }
  }

Now, I am using java route api provided by gateway for configuring my routes, so this is my route code -现在,我正在使用网关提供的 java 路由 api 来配置我的路由,所以这是我的路由代码 -

        @Bean
      public RouteLocator myRoutes(RouteLocatorBuilder routeLocatorBuilder) 
{
      return routeLocatorBuilder.routes()
         .route( p -> p.path("/hello").uri("http://localhost:8081"))
        .build();
}

Now, I want to know how to add the custom filter factory which i just created to the route defined above programmatically.现在,我想知道如何以编程方式将我刚刚创建的自定义过滤器工厂添加到上面定义的路由中。

I have looked at the following examples where they register a custom filter factory -我查看了以下示例,他们在其中注册了自定义过滤器工厂-

  1. https://www.javainuse.com/spring/cloud-filter
  2. https://medium.com/@niral22/spring-cloud-gateway-tutorial-5311ddd59816

Both of them create routes using properties rather than using the route api.他们都使用属性创建路由,而不是使用路由 api。

Any help is much appreciated.任何帮助深表感谢。

This solution worked for me, I created an OrderedGatewayFilter with the injected CustomGatewayFilterFactory like this and added that filter to routes:这个解决方案对我有用,我像这样使用注入的 CustomGatewayFilterFactory 创建了一个 OrderedGatewayFilter,并将该过滤器添加到路由中:

@Bean
public RouteLocator myRoutes(RouteLocatorBuilder routeLocatorBuilder, CustomGatewayFilterFactory customGatewayFilterFactory) 
{
    OrderedGatewayFilter orderedGatewayFilter =
      new OrderedGatewayFilter(customGatewayFilterFactory.apply(config), 45);
    return routeLocatorBuilder.routes()
         .route( p -> p.path("/hello").uri("http://localhost:8081").filter(orderedGatewayFilter))
        .build();
}

You need to inject your custom Filter and include it in the route.您需要注入您的自定义过滤器并将其包含在路由中。 Something like this..像这样的东西。。

        @Bean
      public RouteLocator myRoutes(RouteLocatorBuilder routeLocatorBuilder, CustomPreFilterFactory cpf) 
{
      return routeLocatorBuilder.routes()
         .route( p -> p.path("/hello").filters(f -> f.filter(myCustomFilter.apply(new Config()))).uri("http://localhost:8081"))
        .build();
}

Below is an example of a route that has a predicate defined to match all the request URL with /api/v1/first/** and apply a pre-filter to rewrite the path.下面是一个路由示例,它定义了一个谓词来匹配所有请求 URL 和 /api/v1/first/** 并应用预过滤器来重写路径。 There is another filter applied to modify the request header and then route the request to load balanced FIRST-SERVICE.应用了另一个过滤器来修改请求 header,然后将请求路由到负载均衡的 FIRST-SERVICE。

builder.routes()
            .route(r -> r.path("/api/v1/first/**")
                    .filters(f -> f.rewritePath("/api/v1/first/(?.*)", "/${remains}")
                                    .addRequestHeader("X-first-Header", "first-service-header")
                    )
                    .uri("lb://FIRST-SERVICE/") //downstream endpoint  lb - load balanced
                    .id("queue-service"))

            .build();

Below is the equivalent.yaml configuration.下面是等效的.yaml配置。

spring:
  cloud:
    gateway:
      routes:
      - id: first-service
        uri: lb://FIRST-SERVICE
        predicates:
        - Path=/api/v1/first/**
        filters:
        - RewritePath=/api/v1/first/(?.*), /$\{remains}
        - AddRequestHeader=X-first-Header, first-service-header

You can find more such filters in this link.您可以在此链接中找到更多此类过滤器。

Hope this is what you are looking for.希望这是您正在寻找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM