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 toPRODUCTSERVICE, which is registered in Spring Cloud Load Balancer.
Example Routing Behavior
| Incoming Request | Rewritten Path | Forwarded To |
/eshop/productservice/items | /items | PRODUCTSERVICE |
/eshop/productservice/category/electronics | /category/electronics | PRODUCTSERVICE |
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.
