Gateway Indicates the new generation Gateway
Zuul Routing gateway
Zuul’s core staff lost two. The development of Zuul2 took too long, and Spring couldn’t wait to develop its own Gateway.
Introduction to the
One of the most important components of the Cloud bucket is the gateway. In the 1.x version, the Zuul gateway is used. However, in the 2.x release, Zuul was upgraded in a consistent manner, and SpringCloud eventually developed its own Gateway to replace Zuul, the SpringCloud Gateway
-
Gateway is an API Gateway service built on top of the Spring ecosystem, based on Spring 5,Spring Boot 2, and Project Reactor technologies.
-
Gateway is designed to provide a simple and efficient way to route apis and provide powerful peer filters such as fuses, traffic limiting, retry, and so on
-
Gateway, as the target of SpringCloud, provides unified and equal routing mode, and provides basic Gateway functions based on Filter chain, such as security and monitoring. Current limiting
-
SpringCloud Gateway uses reactor-NetTY responsive programming in Webflux, and netTY communication framework is used at the bottom
! [Insert picture description here]img-blog.csdnimg.cn/! [202008300…
Because Zuul1.0 is in maintenance and the Gateway was developed by the SpringCloud team, it is much more convenient than Zuul
Gateway is developed on an asynchronous, non-blocking model, and performance is not a concern
Differences between SpringCloud Gateway and Zuul
Three core concepts
Route
- A route is the basic building block of a gateway. It consists of an ID, a destination URL, a set of assertions, and filters that match the route if the assertion is true
Predicate.
- Reference is Java8 Java. Util. The function. The predicate
- A developer can match everything in an HTTP request (such as request headers or request parameters) and route the request if it matches an assertion
Filter
- An instance of GatewayFilter in the Spring framework, which allows requests to be modified before or after the request is routed.
The overall
- Web request, through some matching criteria, to locate the real service node. And before and after this makeup hair process, undertake a few fine refinement control.
- Predicate is where we match conditions; A filter, on the other hand, can be interpreted as an omnipotent interceptor. With these two elements, plus the target URI, a specific route can be implemented
Gateway Workflow
(Summary on official website)
Demo
- Create module cloud-gateway-gateway9527
- The introduction of pom
<dependencies> <! --gateway--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <! -- Reference your own API generic package, Payment Entity --> <dependency> <groupId>com.angenin.springcloud</groupId> <artifactId>cloud-api-commons</artifactId> <version>${project.version}</version> </dependency> <! --eureka client(Dynamic routing through microservice name)--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <! > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Copy the code
- Yml file
server:
port: 9527Spring: application: name: cloud-gateway Cloud: gateway: routes: -id: payment_route # http://localhost:8001
predicates:
- Path=/payment/get-id: payment_route2 URI: http://localhost:8001 Eureka: instance: hostname: cloud-gateway-service client: fetch-registry: Path=/payment/lb/** # true register-with-eureka: true service-url: defaultZone: http://eureka7001.com:7001/eureka/Copy the code
- The main start class
@SpringBootApplication
@EnableEurekaClient
public class GatewayMain9527 {
public static void main(String[] args) { SpringApplication.run(GatewayMain9527.class, args); }}Copy the code
- Start the Eureka Server 7001 Client 8001 + Gateway 9527
Access to 8001 through our 9527 gateway
Here’s where it works
Gateway Indicates the two modes of configuring Gateway routes
- In the configuration file
In the configuration file yML
- Configure in the configuration class
A Bean injected into the RouteLocator code
Case study (visit Baidu)
The new config. GatewayConfig
package com.yxl.cloud.config;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
routes.route("path_route_angenin".//id
r -> r.path("/guonei") / / http://localhost:9527/guonei
.uri("http://news.baidu.com/guonei")); / / will be forwarded to http://news.baidu.com/guonei
routes.route("path_route_angenin2".//id
r -> r.path("/guoji") / / http://localhost:9527/guoji
.uri("http://news.baidu.com/guoji")); / / will be forwarded to http://news.baidu.com/guonji
returnroutes.build(); }}Copy the code
Access:http://localhost:9527/guonei
Dynamic routing is implemented through microservice names
server:
port: 9527
spring:
application:
name: cloud-gateway
cloud:
gateway:
discovery:
locator:
enabled: true# enable dynamic route creation from registry using microservice names (default)false) routes: -id: payment_route # id of the route.//localhost:8001 # Specifies the route address to provide services
uri: lb://cloud-provider-hystrix-payment
predicates:
- Path=/payment/get-id: payment_route2 # uri: http://localhost:8001 uri: Lb ://cloud-provider-hystrix-payment predicates: -path =/payment/lb/** # cloud-gateway-service client: fetch-registry: true register-with-eureka: true service-url: defaultZone: http://eureka7001.com:7001/eureka/Copy the code
The use of the Predicate
Website:Cloud. Spring. IO/spring – clou…
SpringCloud Gateway uses route matching as part of the Spring WebFlux HandlerMapping infrastructure.
The SpringCloud Gateway includes a number of built-in Route Predicate factories. All of these predicates match different properties of the HTTP request. Multiple Route Predicate factories can be combined
When SpringCloud Gateway creates the Route object, it uses RoutePredicateFactory to create the Predicate object, which can be assigned to the Route. The Springcloud Gateway contains a number of built-in Route Predicate Factories.
All of these verbs match different attributes of HTTP requests, and multiple predicate factories can be combined, via logical and
Simple to use
public class T2 {
public static void main(String[] args) {
// Get the current time string
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now);
: / / 2020-06-17 T11 53:40. 325 + 08:00 Asia/Shanghai}}Copy the code
# set time Before access (Before) - Before=2020-06-17T11:53:40.325+ 08:00[Asia/Shanghai]
#指定时间内才能访问(Between)
- Between=2020-06-17T11:53:40.325+ 08:00[Asia/Shanghai],2020-06-17T12:53:40.325+ 08:00[Asia/Shanghai]
Copy the code
Cookie
Yml setting cookies
- Cookie=username,angenin # with Cookie, and the value of username is angeninCopy the code
The direct access without cookie failed
Header
# - After=2020-06-17T12:53:40.325+ 08:00[Asia/Shanghai] # -cookie = angenin # If the value of username is angenin-header = x-request-id, \d+ # the Request Header must have the x-request-id attribute and the value of the regular expression is integerCopy the code
Method
- Method=GET # Only GET requests are allowedCopy the code
conclusion
The use of the Filter
Routing filters can be used to modify incoming HTTP requests and returned HTTP responses. Routing filters can only be used by specified routes.
The SpringCloud Gateway has a variety of routing filters built in, all generated by the Factory class of GatewayFilter
GatewayFilter (31 kinds) Global Filter (10 kinds)
package com.yxl.cloud.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Date;
@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter.Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info(**************come in MyLogGateWayFilter: + new Date());
String uname = exchange.getRequest().getQueryParams().getFirst("uname");
if(uname ==null){
log.info("******* user name null, illegal user!!");
// Set response, not accepted
exchange.getResponse().setStatusCode(HttpStatus.NO_CONTENT);
return exchange.getResponse().setComplete();
}
// Chain. Filter (exchange) is displayed
return chain.filter(exchange);
}
@Override
public int getOrder(a) {
return 0; }}Copy the code
http://localhost:9527/payment/lb?xxx=111
- Personal blog: blog.yanxiaolu.cn /