3

So I am new to spring cloud gateway and have just started playing around with it . 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 -

        @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 .

Any help is much appreciated.

Indraneel Bende
  • 3,196
  • 4
  • 24
  • 36

3 Answers3

1

This solution worked for me, I created an OrderedGatewayFilter with the injected CustomGatewayFilterFactory like this and added that filter to routes:

@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();
}
0

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. There is another filter applied to modify the request header and then route the request to load balanced 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.

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.

Vijay
  • 558
  • 6
  • 22
  • The questioner is asking how to add his custom filter "CustomPreFilterFactory". Not existing filters offered by Spring Cloud. – rakesh mehra Sep 19 '20 at 10:56
0

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();
}
rakesh mehra
  • 618
  • 1
  • 9
  • 21