Build API Gateway using Spring Cloud Gateway

I showed you how to build an API Gateway using Zuul Proxy of Spring Cloud Netflix. In this tutorial, I introduce to you another way, using another library in the Spring framework ecosystem, that is, Spring Cloud Gateway!

To put it simply, in principle, an API Gateway will allow us to configure it so that when one request comes to it, this request will be forwarded to this service, and the other will be forwarded to that service. Spring Cloud Gateway has the same function. The Spring Cloud Gateway supports us with filters, so we can change any request to internal services such as adding request parameters, changing request URLs, adding headers, and so on… We can add new custom filters, meaning you can write Java code, to add any other processing logic before a request is actually forwarded to the target service.

Spring Cloud Gateway also supports Service Discovery like Zuul Proxy of Spring Cloud Netflix. But in this tutorial, just to give you an overview of how Spring Cloud Gateway works, I will just create an example with a project using Spring Cloud Gateway as an API Gateway and a other acts as the service we need to call.

First, I will create a new Spring Boot project implementation a service that you need to call with an API with the following content:

Result:

Build API Gateway using Spring Cloud Gateway

Next, I will also create a new Spring Boot project with Spring Cloud Gateway dependency to do API Gateway as follows:

Build API Gateway using Spring Cloud Gateway

Result:

Build API Gateway using Spring Cloud Gateway

To configure services in Spring Cloud Gateway, we have 2 ways: using properties or using Java code provided by Spring Cloud Gateway. In this tutorial, I will guide you to use the properties!

You should use the application.yaml file, it will be easier for this configuration.

Build API Gateway using Spring Cloud Gateway

We will use a set with at least the following properties to configure a service:

We can define multiple services, corresponding to each service as an element in routes with the id definition to identify the service, uri as the host information, port and predicates as the list of requests that API Gateway will catch up and forward the request from the user to that service. Eg:

In my example, you can configure the above service information in API Gateway as follows:

Because the service in this example runs at port 8080, I will configure the API Gateway to run at port 9080.

Run both API Gateway and service, then request to API Gateway with request http://localhost:9080/hello, you will see the same result as above:

Build API Gateway using Spring Cloud Gateway

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment