By Marone: June 2020
Spring Cloud Gateway
Introduction
Table of contents
Goal
In this article we will learn how to use Spring Cloud Gateway, especially how toroute
the incoming requests.
Used tools
Java 11Maven 3.x
cURL 7.x
What is Spring Cloud Gateway
Spring Cloud Gateway is a non blocking and a open source API Gateway. It is built on top of the Spring Ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. The Gateway is about routing requests/responses between clients and API's and provide some central cross-cutting capabilities such as security, metrics, ...etc.Routing
There are two ways to create Routing, using java DSL or by using configuration files. In this article we will use the Java Way.Building blocks
- Route : The main building block of the gateway. It has:
- an ID, the name of the route
- A destination, which describes where to forward the request
- Predicates and filters
- Predicate : It uses the HTTP request to match the route
- Filter :It intercepts requests/responses, so they can be modified and updated.
Maven dependency
Create Routing
There are three routes defined.
Simple Route
It has an ID simple_route and a destination http://httpbin.org and one predicate /getThe send request is http://localhost:9001
/get
, Spring reads the request URL and checks if the path equals to /get
. If it is true the request will be forward to the target destination . Just keep in mind the path part has been appended to end of the destination http://httpbin.org/get
The external Route
This route is almost similar to the previous one except the filter part. With
stripPrefix(1)
the path part will be stripped from the target url
Instead of sending http://httpbin.org
/external-api
/get the gateway sends only http://httpbin.org/get
The Host Route
The third route is little bit different, it has an ID and a destination BUT a predicate based onhost
. The request sould contain a special information to indicate the host.
In order to use host you have to map the IP address to host name. The hosts file on windows will look like:
The host information has been send as a request header
References
The complete code can be found in GitHub