By Marone: June 2020
GoalIn this article we will learn how to use Spring Cloud Gateway, especially how to
routethe incoming requests.
Used toolsJava 11
What is Spring Cloud GatewaySpring 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 capabilites such as security, metrics, ...etc.
RoutingThere are two ways to create Routing, using java DSL or by using configuration files. In this article we will use the Java Way.
- 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.
There is three routes defined.
First RouteIt has an ID simple_route and a destination http://httpbin.org and one predicate /get
The 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
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
Third RouteThe third route is little bit different, it has an ID and a destination BUT a predicate based on
host. 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
The complete code can be found in GitHub