GateWay
A brief introduction
1, the website
Cloud. Spring. IO/spring – clou…
2, an overview of the
SpringCloud Gateway is a new Project of SpringCloud, which is developed based on Spring 5.0+Spring Boot 2.0 and Project Reactor. It aims to provide a simple and effective unified API routing management approach for microservices architecture.
As a Gateway in the SpringCloud ecosystem, SpringCloud Gateway aims to replace Zuul. In SpringCloud 2.0 or above, there is no integration for the latest high-performance version of Zuul 2.0 or above. It is still an old version of the Zuul 1.x non-reactor model. In order to improve the performance of the Gateway, SpringCloud Gateway is implemented based on the WebFlux framework, and the underlying layer of the WebFlux framework uses the high-performance Reactor mode communication framework Netty.
The goal of the Spring Cloud Gateway is to provide a unified routing mode and provide basic Gateway functions such as security, monitoring/metrics, and traffic limiting based on the Filter chain.
Summary: The Reactor-Netty responsive programming component of Webflux used by SpringCloud Gateway uses the Netty communication framework.
3. What can I do
Reverse proxy, authentication, flow control, circuit breaker, and log monitoring……
4. Where is the gateway in the microservices architecture
5, how to have Zuul out of the gateway
(1) Why do you choose Gateway
①neflix is not quite reliable, but zuul2.0 has been delayed to release.
②SpringCloud Gateway has the following features:
** Build based on Spring Framework 5, Project Reactor and Spring Boot 2.0; ** Dynamic routing: can match any request attribute; You can specify Predicate and Filter for routes. Integrated circuit breaker function with Hystrix; Integrating Spring Cloud service discovery capabilities; Predicate and Filter, which are easy to write; Request traffic limiting function; Support path rewriting.
The difference between SpringCloud Gateway and Zuul
Zuul 1.x is an API Gateway based on blocking I/ O, using the blocking architecture based on Servlet 2. 5.
(2) Zuul1. X model
The version of Zuul integrated in Springcloud uses a Tomcat container and the traditional Servlet IO processing model.
Life cycle management of servlets is performed by Servlet Container. Container starts by constructing the servlet object and calling servlet init() to initialize it; The container runtime accepts requests, assigns a thread to each request (typically fetching idle threads from the thread pool), and then calls service(); When the container closes, the servlet deStory () is called to destroy the servlet.
This model works well for low concurrency scenarios with servlets, but when concurrency is high (such as jemeter pressure), the number of threads increases and the cost of threads is high (thread switching, memory consumption), which seriously affects the processing time of requests.
(3) the GateWay model
The bottom layer uses WebFlux and Netty.
Traditional Web frameworks, such as StrutS2, SpringMVC, etc., run on top of the Servlet API and Servlet container. However, asynchronous non-blocking support was introduced after Servlet3.1. WebFlux is a typical non-blocking asynchronous framework, its core is based on the Reactor API implementation. In contrast to traditional web frameworks, it can run on containers such as Netty, Undertow, and Servlet3.1. Non-blocking + functional programming (Spring5 must let you use java8).
Spring WebFlux is a new responsive framework introduced by Spring 5.0. Unlike Spring MVC, it does not rely on the Servlet API. It is fully asynchronous and non-blocking, and is based on the Reactor to implement the responsive streaming specification.
Two, three core concepts
1, Route(Route)
A route is the basic building block of a gateway. It consists of an ID, a target URI, a series of assertions and filters that match the route if the assertion is true.
2. Predicate(Predicate)
Reference is Java8 Java. Util. The function. The Predicate, the developer can match all the content in the HTTP request (for example, request or request parameters), if the request is match the assertion is routed.
3, Filter
Refers to an instance of a GatewayFilter in the Spring framework that allows you to modify a request before or after it is routed.
4, the overall
The Web request, through some matching criteria, locates to the real service node. And before and after this forwarding process, some fine control. Predicate is our matching condition; Filter, on the other hand, can be understood as an omnipotent interceptor. With these two elements, and the target URI, you can implement a specific route.
Iii. Gateway workflow
1, the official website summary
The client sends a request to the Spring Cloud Gateway. The route that matches the request is then found in the Gateway Handler Mapping and sent to the Gateway Web Handler.
The Handler then sends the request through the specified filter chain to our actual service to perform the business logic and then returns. The filters are separated by dashed lines because the filters may execute business logic before (” pre “) or after (” POST “) the proxy request is sent.
Filter The pre Filter can perform parameter verification, permission verification, traffic monitoring, log output, and protocol conversion. The POST Filter can modify the response content and response header, which plays an important role in log output and traffic monitoring.
2. Core logic
Route forwarding + execution filter chain
4. Getting Started
1. Create a Module
cloud-gateway-gateway9527
2, POM
<! --gateway--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <! --eureka-client// Zookeeper, consul can also -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
Copy the code
3. Added gateway configuration in YML
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
routes:
- id: payment_routh #payment_route # Specifies the ID of the route. It has no fixed rules but must be unique
uri: http://localhost:8001 # Route address to provide service after matching
predicates:
- Path=/payment/get/** # assertion, the path matches the route
- id: payment_routh2 #payment_route # Specifies the ID of the route. It has no fixed rules but must be unique
uri: http://localhost:8001 # Route address to provide service after matching
predicates:
- Path=/payment/lb/** # assertion, the path matches the route
eureka:
instance:
hostname: cloud-gateway-service
client: The service provider registers with the Eureka service list
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eureka
Copy the code
4. No service
5, the main boot class
@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527 {
public static void main(String[] args) { SpringApplication.run(GateWayMain9527.class,args); }}Copy the code
6, test,
Enable gateway 7001, gateway 8001 (cloud-Provider-Payment8001), and gateway 9527
Add the gateway before: http://localhost:8001/payment/get/31
After adding gateway: http://localhost:9527/payment/get/31
7. Gateway Another configuration mode
Inject a RouteLocator Bean into your code
@Configuration
public class GateWayConfig{
Configured with a / * * * id for the route - the name of the routing rules, * when access the address http://localhost:9527/guonei will be automatically forwarded to the address: http://news.baidu.com/guonei *@param builder
* @return* /
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder){
RouteLocatorBuilder.Builder routes = builder.routes();
routes.route("path_route_atguigu", r -> r.path("/guonei").uri("http://news.baidu.com/guonei")).build();
return routes.build();
}
@Bean
public RouteLocator customRouteLocator2(RouteLocatorBuilder builder){
RouteLocatorBuilder.Builder routes = builder.routes();
routes.route("path_route_atguigu2", r -> r.path("/guoji").uri("http://news.baidu.com/guoji")).build();
returnroutes.build(); }}Copy the code
Implement dynamic routing through microservice name
By default, the Gateway creates a dynamic route based on the service list registered in the registry and the micro-service name path in the registry for forwarding, thus realizing the dynamic routing function.
1, start,
One eureka7001 + two service providers 8001/8002
2, POM
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
Copy the code
3, YML
Note that the PROTOCOL of the URI is LB, indicating that the load balancing function of the Gateway is enabled.
Lb ://serviceName is the load balancing URI that spring Cloud Gateway automatically creates for us in the microservice.
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true # Enable dynamic route creation from the registry, using microservice names for routing
routes:
- id: payment_routh #payment_route # Specifies the ID of the route. It has no fixed rules but must be unique
# uri: http://localhost:8001 # Match the routing address of the service
uri: lb://cloud-payment-service # Route address to provide service after matching
predicates:
- Path=/payment/get/** # assertion, the path matches the route
- id: payment_routh2 #payment_route # Specifies the ID of the route. It has no fixed rules but must be unique
# uri: http://localhost:8001 # Match the routing address of the service
uri: lb://cloud-payment-service # Route address to provide service after matching
predicates:
- Path=/payment/lb/** # assertion, the path matches the route
eureka:
instance:
hostname: cloud-gateway-service
client: The service provider registers with the Eureka service list
service-url:
register-with-eureka: true
fetch-registry: true
defaultZone: http://eureka7001.com:7001/eureka
Copy the code
4, test,
http://localhost:9527/payment/lb
8001/8002 Port switchover
Use of Predicate
1, Route Predicate Factories
The Spring Cloud Gateway provides route matching as part of the Spring WebFlux HandlerMapping infrastructure.
Spring Cloud Gateway includes a number of built-in Route Predicate factories. All of these predicates match the different properties of the HTTP request. Multiple Route Predicate factories can be combined.
When the Spring Cloud Gateway creates a Route object, it uses RoutePredicateFactory to create Predicate objects, which can be assigned to a Route.
The Spring Cloud Gateway contains many built-in Route Predicate Factories.
All of these predicates match different attributes of the HTTP request. Multiple predicate factories can be combined by logical and.
2, the common Route Predicate
(1)After Route Predicate
public class ZonedDateTimeDemo{
public static void main(String[] args){
ZonedDateTime zbj = ZonedDateTime.now(); // Default time zone
System.out.println(zbj);
// ZonedDateTime zny = ZonedDateTime.now(ZoneId.of("America/New_York")); // Get the current time with the specified time zone
// System.out.println(zny);}}Copy the code
predicates:
- Path=/payment/lb/** # assertion, the path matches the route
- After = 2020-02-05 T15:10:03. 685 + 08:00 Asia/Shanghai # assertion, the path matches the route
Copy the code
(2)Before Route Predicate
- Before = 2020-02-05 T15:10:03. 685 + 08:00 Asia/Shanghai # assertion, the path matches the route
Copy the code
(3)Between Route Predicate
- Between = 2020-02-02 T17:45:06. 206 + 08:00 Asia/Shanghai, the 2020-03-25 T18:59:06. 206 + 08:00 Asia/Shanghai
Copy the code
(4)Cookie Route Predicate
Cookie Route Predicate takes two arguments, a Cookie name and a regular expression. The routing rule will obtain the corresponding Cookie name value and the regular expression to match. If there is a match, the route will be executed. If there is no match, the route will not be executed.
- Cookie=username,zzyy
Copy the code
(5)Header Route Predicate
Two parameters: one is the property name and a regular expression. If the property value matches the regular expression, it is executed.
- Header=X-Request-Id, \d+ # A regular expression with the x-request-id attribute and an integer value in the Request header
Copy the code
(6)Host Route Predicate
The Host Route Predicate takes a set of parameters, a list of domains that match, and this template is an Ant separated template that uses. The number is used as the separator. It uses the host address in the parameter as the matching rule.
- Host=**.atguigu.com
Copy the code
(7)Method Route Predicate
- Method=GET
Copy the code
(8)Path Route Predicate
- Path=/payment/lb/** # assertion, the path matches the route
Copy the code
(9)Query Route Predicate
Supports passing two parameters, one is the property name and the other is the property value, which can be a regular expression.
- Query=username, \d+ # Route only if the parameter username is an integer
Copy the code
Small summary (10)
The Predicate implements a set of matching rules for the request to find the corresponding Route for processing.
7. Use of Filter
1. What is it
The route filter can be used to modify the incoming HTTP request and the returned HTTP response. The route filter can only be used to specify routes.
Spring Cloud Gateway has several built-in routing filters that are generated by the GatewayFilter factory class.
2. Spring Cloud Gateway Filter
(1) Life cycle
The pre and post
(2) types
GatewayFilter, GlobalFilter
3. Commonly used GatewayFilter
AddRequestParameter
filters:
- AddRequestParameter=X-Request-Id,1024 # Filter factory will add a pair of Request headers with the x-request-id value of 1024 to the matched Request headers
Copy the code
4, custom filter (custom GlobalFilter)
(1) Introduction of two main interfaces
implements GlobalFilter,Ordered
(2) can do
Global logging, unified Gateway Authentication……
(3) Case code
@Component // Must add, must add, must add
public class MyLogGateWayFilter implements GlobalFilter.Ordered{
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain){
System.out.println("time:"+new Date()+"\t executes custom global filters:"+"MyLogGateWayFilter"+"hello");
String uname = exchange.getRequest().getQueryParams().getFirst("uname");
if (uname == null) {
System.out.println("**** user name is null, cannot log in");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
@Override
public int getOrder(a){
return 0; }}Copy the code
(4) test
http://localhost:9527/payment/lb?uname=z3