preface
Article content output source: Pull hook education Java high salary training camp;
After learning the architecture of microservices in pull boot camp, Gateway is still very popular as a Gateway service, compiled the following notes.
GateWay profile
GateWay (translated as GateWay) : An important part of microservices architecture. The LAN has the concept of gateway. The LAN receives or sends data through this gateway. For example, when Vmware virtual machine software is used to build virtual machine clusters, we often need to select an IP address in the IP segment as the gateway address.
Spring Cloud GateWay is a new project from Spring Cloud that aims to replace Netflflix Zuul, It is developed based on Spring5.0+SpringBoot2.0+WebFlux (Reactor model based on high performance responsive communication framework Netty, asynchronous non-blocking model), and its performance is higher than Zuul. In official tests, GateWay is 1.6 times that of Zuul. It aims to provide a simple and effective unified API route management method for microservices architecture. Spring Cloud GateWay not only provides a unified routing mode (reverse proxy), but also provides basic GateWay functions based on the Filter chain, such as authentication, traffic control, fusing, path rewriting, log monitoring, etc
The location of the gateway in the architecture is shown below
Nginx load balancer (high availability NGINx cluster), where NGINx completes the load on downstream gateway components to achieve high availability of gateway.
The Spring Cloud GateWay is asynchronous and non-blocking by nature, based on the Reactor model. A request – > the gateway matches according to certain conditions – then forwards the request to the specified service address; In the process, we can do some more specific controls (limiting traffic, logging, whitelist).
- Route: The most basic part of a gateway and the basic unit of work of the gateway. A route consists of an ID, a destination URL (the final route to the address), a set of assertions (matching criteria), and a Filter Filter (refinement control). If the assertion is true, the route is matched.
- Predicates: Reference the Java8 assertions in Java. Util. The function. The Predicate, the developer can match all the content in the Http request (including the request headers, request parameters, etc.) (similar to the location of nginx matching), if the assertion match the request routing.
- Fifilter: A standard Spring webFilter that uses filters to execute business logic before or after a request.
An image from the official website
Among them, Predicates predicate is our matching condition, and Filter can be understood as an omnipotent interceptor. With these two elements, combined with the target URL, a specific route forwarding can be realized.
GateWay working process
Workflow flow chart provided on the official website.
The client sends a request to the Spring Cloud GateWay, then finds the route matching the request in the GateWay Handler Mapping and sends it 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 filter may perform business logic before (PRE) or after (POST) sending the proxy request.
Filter The Pre Filter can perform parameter verification, permission verification, traffic monitoring, log output, and protocol conversion. The POST Filter can perform response content, response header modification, log output, and traffic monitoring.
GateWay core logic: route forwarding + execution filter chain.
The GateWay application
GateWay does not use web modules and introduces WebFlux (similar to SpringMVC).
Rely on
The pom.xml file is as follows:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <! - GateWay GateWay - > <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <! - introduce webflux -- -- > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <! -- Log dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </dependency> <! -- Test dependencies --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! - lombok tools - > <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> The < version > 1.18.4 < / version > <scope>provided</scope> </dependency> <! -- Introducing Jaxb, start --> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> The < version > 2.2.11 < / version > </dependency> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> The < version > 2.2.11 < / version > </dependency> <dependency> <groupId>org.glassfish.jaxb</groupId> <artifactId>jaxb-runtime</artifactId> < version > 2.2.10 - b140310.1920 < / version > </dependency> <dependency> <groupId>javax.activation</groupId> <artifactId>activation</artifactId> The < version > 1.1.1 < / version > </dependency> <! -- Introducing Jaxb, end <! -- Actuator helps you monitor and manage Spring Boot apps --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <! -- Hot deployment --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <! -- Link Tracing --><! --<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-sleuth</artifactId> </dependency>--> </dependencies> <dependencyManagement> <! -- Spring Cloud relies on version management --> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Greenwich.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> Copy the code
configuration
server:
port: 9002
eureka:
client:
serviceUrl: Path to eureka Server
defaultZone: http://democloudeurekaservera:8761/eureka/,http://democloudeurekaserverb:8762/eureka/ Eureka server can synchronize the registry with each eureka server instance: Use the IP address to register, otherwise the host name will be registered. prefer-ip-address: true # customize the display format of the instance, plus the version number, convenient multi-version management, note that the address is ip-address, the earlier version is ipAddress instance-id: ${spring.cloud.client.ip-address}:${spring.application.name}:${server.port}:@project.version@ spring: application: name: lagou-cloud-gateway cloud: gateway: routes: There can be multiple routes - id: service-autodeliver-router # our custom route ID, keep unique # URI: http://127.0.0.1:8096 # Destination service address Automatic delivery micro service (deploy multiple instances) Dynamic routing: THE URI configuration should be a service name, not the address of a specific service instance uri: lb://demo-service-autodeliver The gateway gets instance information from the service registry and loads the route back predicates: Predicate: Route conditions, Predicate takes an input parameter and returns a Boolean result. The interface contains multiple tacit methods for grouping Predicate into other complex logic (for example, and, or, or not). - Path=/autodeliver/** - id: service-resume-router # our custom route ID, keep unique #uri: http://127.0.0.1:8081 # Destination service address #http://localhost:9002/resume/openstate/1545132 # http://127.0.0.1:8081/openstate/1545132 uri: lb://demo-service-resume Predicate: Route conditions, Predicate takes an input parameter and returns a Boolean result. The interface contains multiple tacit methods for grouping Predicate into other complex logic (for example, and, or, or not). predicates: - Path=/resume/** filters: - StripPrefix=1 Copy the code
A routing rule with id service-autoDeliver -router is configured when the gateway is initiated
request
http://localhost:9002/autodeliver/checkAndBegin/1545132
Copy the code
The request is routed to the corresponding microservice.
GateWay Description of routing rules
Spring Cloud GateWay helps us to build many Predicates functions, realizing various routing matching rules (through headers, request parameters, etc.) to match the corresponding routing.
Match after point in time
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: T17 - After = 2017-01-20:42:47. 789 - from America/DenverCopy the code
Match before time point
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: T17 - Before = 2017-01-20:42:47. 789 - from America/DenverCopy the code
Time interval matching
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: T17 - Between = 2017-01-20:42:47. 789 - from America/Denver, 2017-01-21 T17:42:47. 789 - from America/DenverCopy the code
Specifies that the Cookie re matches the specified value
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: - Cookie=chocolate, ch.p Copy the code
Specifies that the Header re matches the specified value
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: - Header=X-Request-Id, \d+ Copy the code
Request Host to match the specified value
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: - Host=**.somehost.org,**.anotherhost.org Copy the code
Request Method Matches the specified request Method
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: - Method=GET,POST Copy the code
Request a path regex match
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: - Path=/red/{segment},/blue/{segment} Copy the code
The request contains a parameter
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: - Query=green Copy the code
The request contains a parameter whose value matches the regular expression
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: - Query=red, gree. Copy the code
Remote address matching
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org predicates: - RemoteAddr = 192.168.1.1/24Copy the code
GateWay supports automatic retrieval and access of a list of services from a registry, known as dynamic routing
The implementation steps are as follows
1) Add registry client dependencies to POM.xml (because eureka client has been introduced to get registry service list)
2) Dynamic routing configuration
uri: lb://demo-service-resume
Copy the code
Note: When setting up dynamic routes, the URI starts with lb: // (lb stands for service from registry) followed by the name of the service to be forwarded to
GateWay filter
In terms of filter life cycle (influencing timing points), there are two main pre and Post:
-
Pre: This filter is invoked before the request is routed. We can use this filter to authenticate, select requested microservices in the cluster, log debugging information, and so on.
-
Post: This filter is executed after routing to the microservice. Such filters can be used to add standard HTTPheaders to responses, collect statistics and metrics, send responses from microservices to clients, and so on.
From the perspective of filter types, Spring Cloud GateWay filters are divided into GateWayFilter and GlobalFilter
-
GateWayFilter: Applied to a single route
-
GlobalFilter: Applies to all routes
The Gateway Filter can remove placeholders from urls and forward routes, for example
predicates:
- Path=/resume/**
filters:
- StripPrefix=1 # you can delete resume and forward it
Copy the code
Black and white list
When a request is received, the IP address of the client that sends the request is determined. If the access to the customized GateWay Global Filter is denied in the blacklist, the Global Filter interface can be implemented to implement functions such as blacklists and blacklists and traffic limiting.
/ * ** Defines a global filter that takes effect for all routes* /@Slf4j
@Component // Let the container scan it, which is equivalent to registeringpublic class BlackListFilter implements GlobalFilter, Ordered { // Simulate blacklist (actually can go to database or redis query) private static List<String> blackList = new ArrayList<>(); static { blackList.add("0:0:0:0:0:0:0:1"); // Simulate the local address } / * ** Filter core method* @param Exchange encapsulates the context of request and Response objects* @param chain gateway filter chain (including global filter and single route filter) * @return * / @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // Check whether the client is in the blacklist. If yes, deny access. If no, permit access// Retrieve the Request and Response objects from the context ServerHttpRequest request = exchange.getRequest(); ServerHttpResponse response = exchange.getResponse(); // Get the client IP from the Request object String clientIp = request.getRemoteAddress().getHostString(); // Take clientIp to the blacklist query, if there is no access if(blackList.contains(clientIp)) { // Refuse to visit, returnresponse.setStatusCode(HttpStatus.UNAUTHORIZED); / / status code log.debug("=====>IP:" + clientIp + "In the blacklist, will be denied access!"); String data = "Request be denied!"; DataBuffer wrap = response.bufferFactory().wrap(data.getBytes()); return response.writeWith(Mono.just(wrap)); } // Make a valid request, release, and perform subsequent filters return chain.filter(exchange); } / * ** The return value represents the order (priority) of the current filter, the smaller the value, the higher the priority * @return * / @Override public int getOrder() { return 0; } } Copy the code
GateWay high availability
GateWay as a very core component, if the failure, then all requests may not be routed processing, so we need to do GateWay high availability.
The high availability of GateWay is simple: multiple GateWay instances can be started to achieve high availability, and load balancing devices such as Nginx can be used upstream of GateWay for load forwarding to achieve high availability. Start multiple GateWay instances (let’s say two, one port 9002 and one port 9003) and use Nginx to do the rest
Load proxy. The sample is as follows
Configure multiple GateWay instances
upstream gateway {
Server 127.0.0.1:9002;Server 127.0.0.1:9003;}
location / { proxy_pass http://gateway; } Copy the code
conclusion
Gateway can be used for unified external interfaces, permission verification, whitelist, and so on. It is essential in the Spring Cloud microservices architecture, so get it
This article is formatted using MDNICE