Introduction to Spring Cloud Gateway
The official version of Spring Boot 2 was just released some time ago. Spring Cloud Gateway is based on Spring Boot 2 and is a brand new project of Spring Cloud. The project provides an API gateway built on the Spring ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway is designed to provide a simple and efficient way to send APIs and provide them with cross-cutting concerns such as: security, monitoring/metrics and resilience. The current latest version is v2.0.0.M8, and the official version will also be here soon.
Features of Spring Cloud Gateway:
vs Netflix Zuul
Zuul is based on servlet 2.5 (using 3.x), using the blocking API. It does not support any long connections such as websockets. While Gateway is built on Spring Framework 5, Project Reactor, and Spring Boot 2, using a non-blocking API. Websockets is supported and will be a better development experience because it is tightly integrated with Spring.
Spring Cloud Gateway Introduction Practice
The author has recently studied the source code of Spring Cloud Gateway, and has written articles on source code analysis for most functions, but the official version has not been released after all. This article is an introductory practice, showing several commonly used functions, and looks forward to the release of the latest official version.
Example starts two services: Gateway-Server and user-Server. The simulated scenario is that the client requests the backend service and the gateway provides a unified entrance to the backend service. All the backend services are registered with the service and found Consul (both build zk and Eureka are OK, and I am more accustomed to using Consul). The gateway forwards to specific backend services through load balancing.
User Service
The user service is registered with Consul and provides an interface/test.
rely
The required dependencies are as follows:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency>
Configuration File
spring: application: name: user-service cloud: consult: host: 192.168.1.204 port: 8500 discovery: ip-address: ${HOST_ADDRESS:localhost} port: ${SERVER_PORT:${server.port}} healthCheckPath: /health healthCheckInterval: 15s instance-id: user-${server.port} service-name: userserver: port: 8005management: security: enabled: falseExpose the interface
@SpringBootApplication@RestController@EnableDiscoveryClientpublic class GatewayUserApplication { public static void main(String[] args) { SpringApplication.run(GatewayUserApplication.class, args); } @GetMapping("/test") public String test() { return "ok"; }}Expose/test interface and return ok.
Gateway Services
Gateway service provides a variety of routing configurations, routing assertion factories, and filter factories.
rely
Dependencies that need to be introduced:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-actuator</artifactId></dependency>//Dependency on webflux, it is necessary to introduce <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId></dependency><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-gateway-core</artifactId></dependency>//Service discovery component, excluding web dependencies<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> <version>2.0.0.M6</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </exclusion> </exclusions></dependency>//kotlin dependency<dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-stdlib</artifactId> <version>${kotlin.version}</version> <optional>true</optional></dependency><dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-reflect</artifactId> <version>${kotlin.version}</version> <optional>true</optional></dependency>As mentioned above, kotlin-related dependencies are introduced, and the routing configuration of kotlin needs to be supported here. The use of Spring Cloud Gateway requires excluding web-related configurations. It introduces references to webflux. It will be checked when the application starts and must be introduced.
Routing assertion factory
There are many types of routing assertion factories, depending on the request time, host, path, method, etc. The following definition is a path-based route assertion matching.
@Beanpublic RouterFunction<ServerResponse> testFunRouterFunction() { RouterFunction<ServerResponse> route = RouterFunctions.route( RequestPredicates.path("/testfun"), request -> ServerResponse.ok().body(BodyInserters.fromObject("hello"))); return route;}When the requested path is /testfun, the status code of ok is directly returned, and the response body is a hello string.
Filter factory
Gateways often need to filter routing requests and perform some operations, such as constructing headers after authentication. There are many types of filtering, such as adding request headers, adding request parameters, adding response headers and circuit breakers, etc.
@Beanpublic RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) { //@formatter:off return builder.routes() .route(r -> r.path("/image/webp") .filters(f -> f.addResponseHeader("X-AnotherHeader", "baz")) .uri("http://httpbin.org:80") ) .build(); //@formatter:on}As above, when the request path is /image/webp, the request is forwarded to http://httpbin.org:80, and the response is filtered, adding the response header X-AnotherHeader: baz.
Custom routing
The above two subsections belong to API custom routing, and can also be defined through configuration:
spring: cloud: gateway: locator: enabled: true default-filters: - AddResponseHeader=X-Response-Default-Foo, Default-Bar routes: # =========================================================================================================================================================================================================================================================================================================================================================================================================================================================================
The above configuration defines routing and filters. The global filter adds all responses to the header X-Response-Default-Foo: Default-Bar. The route with id default_path_to_http is defined, but the priority is relatively low. When the request cannot match, it will be forwarded to blueskykong.com.
kotlin custom routing
Spring Cloud Gateway can use kotlin to customize routing:
@Configurationclass AdditionalRoutes { @Bean fun additionalRouteLocator(builder: RouteLocatorBuilder): RouteLocator = builder.routes { route(id = "test-kotlin") { path("/image/png") filters { addResponseHeader("X-TestHeader", "foobar") } uri("http://httpbin.org:80") } }}When the requested path is /image/png, it will be forwarded to http://httpbin.org:80, and a filter is set, and an X-TestHeader: foobar header is added to its response header.
Service Discovery Components
Combined with the service registration in the discovery component, forwarded to the specific service instance through serviceId. The corresponding dependencies have been introduced in the previous configuration.
@Beanpublic RouteDefinitionLocator discoveryClientRouteDefinitionLocator(DiscoveryClient discoveryClient) { return new DiscoveryClientRouteDefinitionLocator(discoveryClient);} Inject DiscoveryClient into the constructor of DiscoveryClientRouteDefinitionLocator. The source code analysis will be explained later, and will not be expanded here.
spring: cloud: gateway: locator: enabled: true default-filters: - AddResponseHeader=X-Response-Default-Foo, Default-Bar routes: # =================================================================================- id: service_to_user uri: lb://user order: 8000 predicates: - Path=/user/** filters: - StripPrefix=1
The above configuration enables the implementation of the DiscoveryClient locator. The route defines that all requests that start with /user will be forwarded to the user service, and the path filter will be applied to intercept the first part of the path's prefix. That is, the actual request to access /user/test is converted into lb://user/test.
websocket
You can also configure the gateway routing of websocket:
spring: cloud: gateway: default-filters: - AddResponseHeader=X-Response-Default-Foo, Default-Bar routes: - id: websocket_test uri: ws://localhost:9000 order: 9000 predicates: - Path=/echo
Start a ws server wscat --listen 9000, start the gateway (gateway port is 9090), and connect the client to wscat --connect ws://localhost:9090/echo.
Client access
Readers can download the source code to try the above functions. Here I only show the results of accessing user services:
The gateway successfully load-balanced to user-server and returned ok. The response header contains the global filter settings header X-Response-Default-Foo: Default-Bar
Summarize
In this article, we explore some of the features and components that belong to Spring Cloud Gateway. This new API provides out-of-the-box tools for gateway and proxy support. Looking forward to the official version of Spring Cloud Gateway 2.0.
Source code address
https://github.com/keets2012/Spring-Cloud_Samples
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.