The article directories

  1. I. Overview of Spring Cloud Gateway
    1. 1.1 What is Spring Cloud GateWay
    2. 1.2 Functions of Spring Cloud GateWay
    3. 1.3 Spring Cloud GateWay leaves the incubator
    4. 1.3 Build the Gateway with Spring MVC
      1. 1.3.1 How to Include Spring Cloud Gateway
      2. 1.3.2 Building a Gateway Using Spring MVC
  2. 2.Spring Cloud Gateway MVC module source code analysis
    1. 2.1 Build the Demo of Spring Cloud Gateway
    2. 2.2 Spring Cloud Gateway module source code analysis
    3. 2.3 Code Analysis

Abstract: After The encapsulation of Netflix’s Zuul by Spring Cloud, Spring Cloud Zuul has been used as the gateway of Spring Cloud. The API Gateway is Dead! Long Live the API Gateway! Zuul, Zuul 2, and why Spring Cloud Gateway is available. This article will conduct a demo and brief analysis of the spring-Cloud-gateway-MVC source code.

I. Overview of Spring Cloud Gateway

1.1 What is Spring Cloud GateWay

A Gateway built on Spring Framework 5.0 and Spring Boot 2.0 providing routing and more.

The Spring Cloud Gateway is built on version 5.0 of the Spring Framework and Version 2.0 of Spring Boot to provide routing and other functions.

1.2 Functions of Spring Cloud GateWay

The Spring Cloud GateWay has the following characteristics

  • Java 8/Spring 5/Boot 2
  • WebFlux/Reactor
  • HTTP/2 and Websockets
  • Finchley Release Train (Q4 2017)

Since Spring 5.0 supports Netty, Http2, and Spring Boot 2.0 supports Spring 5.0, it makes sense that the Spring Cloud Gateway supports Netty and Http2. It remains to be seen whether the full Spring Cloud Gateway will be released in Q4 2017.

1.3 Spring Cloud GateWay leaves the incubator

Since December 2016, there has been a Spring Cloud Gateway project on Github at the following address:Github.com/spring-clou…, as shown in the figure below.

After Spring Cloud GateWay left the incubator, the master branch has MVC module. If you want to see the complete other modules, please switch to 2.x branch. Therefore, the design and implementation of core will not be analyzed in this article, which will be covered in a later article.


2.Spring Cloud The Gateway design core code is mainly in Spring-cloud-gateway-core, but since the spring-cloud-gateway-core code is currently moved to 2.x after leaving the incubator, click access is automatically forwarded to github.com/spring- Clou…



As shown in the figure above, at presentThe master branchGateway does not have a core or a starterspring-cloud-gateway-mvcModule, which will be demo and source code analysis in the following sections.

1.3 Build the Gateway with Spring MVC

1.3.1 How to Include Spring Cloud Gateway

To include Spring Cloud Gateway in your project add a dependency with group org.springframework.cloud and artifact id spring-cloud-gateway-mvc. See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

To use spring-cloud-gateway-MVC, just introduce the corresponding spring-cloud-gateway-MVC dependency coordinates.

1.3.2 Building a Gateway Using Spring MVC

Spring Cloud Gateway provides a utility object called ProxyExchange which you can use inside a regular Spring MVC handler as a method parameter. It supports basic downstream HTTP exchanges via methods that mirror the HTTP verbs, or forwarding to a local handler via the forward() method.

Example (proxying a request to “/test” downstream to a remote server):

 @RestController
@SpringBootApplication
public class GatewaySampleApplication {
	@Value("${remote.home}")
	private URI home;
	@GetMapping("/test")
	public ResponseEntity<?> proxy(ProxyExchange<Object> proxy) throws Exception {
		return proxy.uri(home.toString() + "/image/png").get();
	}
}Copy the code

The Spring Cloud Gateway provides a utility object called ProxyExchange that you can use to forward and redirect the build Gateway in the same way that you use the Spring MVC Handler.

For more information :github.com/spring-clou…

2.Spring Cloud Gateway MVC module source code analysis

2.1 Build the Demo of Spring Cloud Gateway

The project of Spring Cloud Gateway has provided me with a project of Spring-cloud-gateway-sample. This project relies on spring-cloud-gateway-MVC, so I need to analyze its source code. Just make sample work normally and it will be ok.

From the project screenshot, compared to the core module I looked at earlier, the MVC module just does a request forwarding.

2.2 Spring Cloud Gateway module source code analysis

1. In spring-cloud-gateway-sample, add the application name and port configuration to application.yml

server: port: 8080 spring: application: name: sc-gw management: security: enabled: false remote: home: http://httpbin.org # Request forwarding target service UrlCopy the code

2.org.springframework.cloud.gateway.sample.GatewaySampleApplication.java

@RestController @SpringBootApplication public class GatewaySampleApplication { @Value("${remote.home}") private URI home; // @getMapping (path="/test") {// head ="/test"; headers="x-host=png.abc.org") public ResponseEntity<Object> proxy(ProxyExchange<Object> proxy) throws Exception { return  proxy.uri(home.toString() + "/image/png") .get(header("X-TestHeader", "foobar")); } @GetMapping("/test2") public ResponseEntity<Object> proxyFoos(ProxyExchange<Object> proxy) throws Exception { return proxy.uri(home.toString() + "/image/webp").get(header("X-AnotherHeader", "baz")); } private Function<ResponseEntity<Object>, ResponseEntity<Object>> header(String key, String value) { return response -> ResponseEntity.status(response.getStatusCode()) .headers(response.getHeaders()).header(key, value) .body(response.getBody()); } public static void main(String[] args) { SpringApplication.run(GatewaySampleApplication.class, args); }}Copy the code

2.3 Code Analysis

  • Start GatewaySampleApplication main application, visit http://localhost:8080/test2, the Debug process is as follows.
@GetMapping("/test2")
public ResponseEntity<Object> proxyFoos(ProxyExchange<Object> proxy) throws Exception {
	return proxy.uri(home.toString() + "/image/webp").get(header("X-AnotherHeader", "baz"));
}Copy the code
  • 237 lines of code in proxyexchange.java
Public ProxyExchange < T > uri (String uri) {try {/ / will uri:http://httpbin.org/image/webp, The new URI object returns this. URI = new URI(URI); } catch (URISyntaxException e) { throw new IllegalStateException("Cannot create URI", e); } return this; }Copy the code

Line 628 doExecute in resttemplate.java to implement the remote call using the corresponding httpClient

@Override
public <T> T execute(URI url, HttpMethod method, RequestCallback requestCallback,
		ResponseExtractor<T> responseExtractor) throws RestClientException {
	return doExecute(url, method, requestCallback, responseExtractor);
}Copy the code

The final call code is shown in the figure below. Because the source code is relatively simple, some details of the process are skipped. If you are interested, you can track and understand it yourself.