This article will show a couple of ways on how to route requests to downstream services using Spring Cloud Gateway. In this simple example, the gateway will route to https://dummyjson.com/products.
First of all,
spring-cloud-starter-gateway dependency is required.
pom.xml should look something similar to the one below.
Creating routes via properties
The first approach is to configure routes in application properties.
This approach is quite easy to understand. One thing to note is the
StripPrefix option. In this example, it is set to zero because we don’t want to strip
/products because then the request will go to
https://dummyjson.com instead of
However, I have seen in some production code where the first path variable is indicates which microservice the gateway needs to forward to. Let’s see an example.
In this case, we don’t want to invoke
product-service.yourplatform.com/product-service/products. We want to invoke
product-service.yourplatform.com/products and enabling the
StripPrefix option will definitely help in these situations.
Creating Routing via Java API
Routes can also be configured using Java API. Here is an example.
Spin up the application and hit
/products endpoint and
/products-java endpoint. The results will be the same as they route to the same fake REST API.