Learnitweb

Implementing Custom Routing Using Spring Cloud Gateway

Spring Cloud Gateway provides developers with the flexibility to customize and define their own routing configurations. In this tutorial, we’ll see how to do that.

Configuring RouteLocator

Now, let’s define a custom routing configuration using RouteLocator in a Spring Boot application.

Create RouterLocator bean in the application.

@Bean
    public RouteLocator eshopAppRouterConfig(RouteLocatorBuilder routeLocatorBuilder) {
        return routeLocatorBuilder.routes()
                .route(p -> p.path("/eshop/productservice/**")
                        .filters(f -> f.rewritePath("/eshop/productservice/(?<segment>.*)", "/${segment}"))
                        .uri("lb://PRODUCTSERVICE"))
                .build();
    }

Explanation of the code

  • Path Matching (path(...)): This route matches any request that starts with /eshop/productservice/.
  • Rewrite Path (rewritePath(...)): The filter removes /eshop/productservice/ from the URL before forwarding the request.
  • Load Balancer (uri(...)): The request is routed to PRODUCTSERVICE, which is registered in Spring Cloud Load Balancer.

Example Routing Behavior

Incoming RequestRewritten PathForwarded To
/eshop/productservice/items/itemsPRODUCTSERVICE
/eshop/productservice/category/electronics/category/electronicsPRODUCTSERVICE

addResponseHeaderFilter

You can add a custom header in response like the following:

@Bean
    public RouteLocator eshopAppRouterConfig(RouteLocatorBuilder routeLocatorBuilder) {
        return routeLocatorBuilder.routes()
                .route(p -> p.path("/eshop/productservice/**")
                        .filters(f -> f.rewritePath("/eshop/productservice/(?<segment>.*)", "/${segment}"))
.addResponseHeader("X-Response-Time", LocalDateTime.now().toString()))
                        .uri("lb://PRODUCTSERVICE"))
                .build();
    }

Here, we have added a custom filter X-Response-Time.