Record on November 23, 2021 – service gateway

Time:2022-5-23

Spring cloud gateway is implemented based on Webflux framework, and netty, a high-performance reactor mode communication framework, is used at the bottom of Webflux framework.
A very important component in the cloud family bucket is the gateway, which is in 1 Zuul gateway is adopted in version x;
But in 2 In version x, zuul’s upgrade has been skipping. Spring cloud finally developed a gateway to replace zuul, which is the spring cloud Gateway – in a word, the gateway is the original zuul1 Replacement of version x

Gateway is an API gateway service built on the spring ecosystem and is based on technologies such as spring 5, spring boot 2 and project reactor.
Gateway aims to provide a simple and effective way to route APIs and provide some powerful filter functions, such as fusing, current limiting, Retry, etc.
Spring cloud gateway is a new project of spring cloud. It is a gateway 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 method for microservice architecture.
As a gateway in the spring cloud ecosystem, the goal of spring cloud gateway is to replace zuul. In spring cloud versions above 2.0, the latest performance versions above Zul 2.0 are not integrated, and zuul 1 is still used X is an old version of non reactor mode. In order to improve the performance of the gateway, the spring cloud gateway is implemented based on the Webflux framework, and the bottom layer of the Webflux framework uses the high-performance reactor mode communication framework netty.
The goal of spring cloud gateway is to provide a unified routing method, and the filter chain based method provides the basic functions of the gateway, such as security, monitoring / indicators, and current limiting.
3. Why gateway?
Gateway features

Based on spring framework 5, project reactor and spring boot 2.0;
Dynamic routing: it can match any request attribute;
You can specify predicate and filter for the route;
Integrated circuit breaker function of hystrix;
Integrate spring cloud service discovery function;
Easy to write predicate and filter;
Request current limiting function;
Path rewriting is supported.

The difference between springcloud gateway and zuul

Before the official version of spring cloud Finchley, the gateway recommended by spring cloud was zuul provided by Netflix.
Zuul 1. x. Is an API gateway based on blocking I / O.
Zuul 1. X is based on servlet 2.5 and uses blocking architecture. It does not support any long connections (such as WebSockets). Zuul’s design pattern is more similar to nginx. I/ О All operations are executed by selecting one of the working threads, and the request thread is blocked until the working thread is completed. However, the difference is that nginx is implemented in C + + and zuul is implemented in Java. However, the JVM itself will be loaded slowly for the first time, which makes zuul’s performance relatively poor.
Zuul 2. The X concept is more advanced. It wants to be non blocking based on netty and support long connections, but spring cloud has not been integrated yet. Zuul . X has better performance than zuul 1 X has been greatly improved. In terms of performance, according to the official benchmark, the RPS (requests per second) of spring cloud gateway is 1.6 times that of zuul.
Spring cloud gateway is built on spring framework 5, project reactor and spring boot2 and uses non blocking API.
Spring cloud gateway also supports websocket and is closely integrated with spring to have a better development experience

http://www.bilibili.com/media…
http://www.bilibili.com/media…
http://www.bilibili.com/media…
http://www.bilibili.com/media…
http://www.bilibili.com/media…
http://www.thinksaas.cn/user/…
2、 Three core concepts
1. Three concepts

Route: route is the basic module for building gateway. It is composed of ID, target URI, a series of assertions and filters. If the assertion is true, the route will be matched;
Predicate: the reference is Java. Net of Java 8 util. function. Predict, the developer can match all contents in the HTTP request (such as request header or request parameters), and route if the request matches the assertion;
Filter: refers to the instance of gatewayfilter in the spring framework. Using the filter, you can modify the request before or after it is routed.

2. Gateway workflow

The client sends a request to the spring cloud gateway. Then find the route matching the request in the gateway handler mapping and send it to the gateway web handler.
The handler then sends the request to our actual service through the specified filter chain, executes the business logic, and then returns.
The filters are separated by dashed lines because the filter may execute business logic before (“pre”) or after (“post”) sending the proxy request.
3、 Gateway configuration
1. Environment
New module: cloud gateway gateway 9527
pom:
<?xml version=”1.0″ encoding=”UTF-8″?>
<project xmlns=”http://maven.apache.org/POM/4.0.0″

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
    <artifactId>cloud2021</artifactId>
    <groupId>com.atguigu</groupId>
    <version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-gateway-gateway9527</artifactId>

<dependencies>
    <!--gateway-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!--eureka-client-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <!--  Introduce self-defined API general package, and you can use payment to pay entity -- >
    <dependency>
        <groupId>com.atguigu.springcloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>${project.version}</version>
    </dependency>
    <!-- General basic configuration class -- >
    <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>

</project>
Copy code
yaml:
server:
port: 9527

spring:
application:

name: cloud-gateway

eureka:
instance:

hostname: cloud-gateway-service

Client: # service provider registered in Eureka service list

service-url:
  register-with-eureka: true
  fetch-registry: true
  defaultZone: http://eureka7001.com:7001/eureka

Copy code
Main startup class:
@SpringBootApplication
@EnableEurekaClient
public class GateWayMain9527
{

public static void main(String[] args) {
    SpringApplication.run(GateWayMain9527.class, args);
}

}
Copy code
Business type: None
2. Gateway configuration
In order to ensure route jump, add the following code:
server:
port: 9527

spring:
application:

name: cloud-gateway

#############################Add gateway configuration###########################
cloud:

gateway:
  routes:
    - id: payment_ routh #payment_ The ID of the route # route, which has no fixed rules but requires uniqueness, is recommended to match the service name
      uri:  http://localhost:8001 #Routing address of the service provided after matching
      #Uri: LB: // cloud payment service # matches the routing address of the service
      predicates:
        -Path = / payment / get / * * # asserts that the path matches the route

    - id: payment_ routh2 #payment_ The ID of the route # route, which has no fixed rules but requires uniqueness, is recommended to match the service name
      uri:  http://localhost:8001 #Routing address of the service provided after matching
      #Uri: LB: // cloud payment service # matches the routing address of the service
      predicates:
        -Path = / payment / lb / * * # asserts that the path matches the route

eureka:
instance:

hostname: cloud-gateway-service

Client: # service provider registered in Eureka service list

service-url:
  register-with-eureka: true
  fetch-registry: true
  defaultZone: http://eureka7001.com:7001/eureka

Copy code
Start the test.

This visithttp://localhost:9527/payment…That’s it.
3. Coding mode configuration
The above configuration adopts yaml mode. Now it can be configured using encoding mode.
@Configuration
public class GateWayConfig
{

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder)
{
    RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();

    routes.route("path_route_atguigu",
            r -> r.path("/guonei")
                    .uri("http://news.baidu.com/guonei")).build();

    return routes.build();
}

}
Copy code
Direct accesshttp://localhost:9527/guonei
4、 Dynamic routing based on microservice name
Here we will simulate the way of using gateway to realize dynamic routing instead of ribbon.
The yaml file of module 9527 is modified as follows:
server:
port: 9527

spring:
application:

name: cloud-gateway
Add gateway configuration

cloud:

gateway:
  discovery:
    locator:
      Enabled: true # enables the function of dynamically creating routes from the registry, using the microservice name for routing
  routes:
    - id: payment_ routh #payment_ The ID of the route # route, which has no fixed rules but requires uniqueness, is recommended to match the service name
      #uri:  http://localhost:8001 #Routing address of the service provided after matching
      Uri: LB: // cloud payment service # matches the routing address of the service
      predicates:
        -Path = / payment / get / * * # asserts that the path matches the route

    - id: payment_ routh2 #payment_ The ID of the route # route, which has no fixed rules but requires uniqueness, is recommended to match the service name
      #uri:  http://localhost:8001 #Routing address of the service provided after matching
      Uri: LB: // cloud payment service # matches the routing address of the service
      predicates:
        -Path = / payment / lb / * * # asserts that the path matches the route

eureka:
instance:

hostname: cloud-gateway-service

Client: # service provider registered in Eureka service list

service-url:
  register-with-eureka: true
  fetch-registry: true
  defaultZone: http://eureka7001.com:7001/eureka

Copy code
Start the test: localhost: 9527 / payment / lb. it is found that the polling operation is indeed implemented
5、 Use of predicate
After 9527 was started, these problems were found in the background

Enter the gateway official website (there are on it) and find a total of 11 predictions

What is predicate

Spring cloud gateway takes route matching as part of the spring Webflux handlermapping infrastructure.
Spring cloud gateway includes many built-in route predict factories. All these predictions match the different attributes of the HTTP request. Multiple route predict factories can be combined.
When spring cloud gateway creates a route object, it uses routepredictefactory to create a predicate object, which can be assigned to route. Spring cloud gateway includes many built-in route predict factories.
All of these predicates match different attributes of the HTTP request. Multiple predicate factories can be combined and passed through logical and.
Use of after route predict factory
According to the official website:

Add a line at the bottom of yaml file, but change it to Chinese time:
After testing, it is found that the time in the above format can be obtained:
public class T2 {

public static void main(String[] args) {
    ZonedDateTime zbj = ZonedDateTime.now();
    System.out.println(zbj);
}

}

//Output
//2021-11-23T10:44:35.485+08:00[Asia/Shanghai]
Copy code
Then modify it:
routes:

- id: payment_ routh #payment_ The ID of the route # route, which has no fixed rules but requires uniqueness, is recommended to match the service name
  #uri:  http://localhost:8001 #Routing address of the service provided after matching
  Uri: LB: // cloud payment service # matches the routing address of the service
  predicates:
    - Path=/payment/lb/** 
    - After=2021-11-23T10:44:35.485+08:00[Asia/Shanghai]

Copy code
Then, it means that the above route can only be used after a certain time. Now modify the above after time, and then start the test. It is found that an error is reported, which indicates that it is indeed effective. This method is a bit similar to the second kill scenario or the regular launch of the project.

Use of cookie route predicate
Is to ask whether to bring cookies or what kind of cookies to bring.
Cookie route predicate requires two parameters: Cookie name and regular expression. Routing rules are matched with cookies through regular expressions.

  • id: payment_ routh2 #payment_ The ID of the route # route, which has no fixed rules but requires uniqueness, is recommended to match the service name

    uri: http://localhost:8001#Routing address of the service provided after matching

    Uri: LB: / / cloud payment service # matches the routing address of the service
    predicates:

    • Path = / payment / lb / * * # asserts that the path matches the route
    • After=2021-11-23T10:44:35.485+08:00[Asia/Shanghai]
    • Cookie=username, James

    Copy code
    The request is sent in curl:

Others can be written according to the official website.
6、 Use of filter
The routing filter can be used to modify the incoming HTTP request and the returned HTTP response. The routing filter can only be used by specifying the route. Spring cloud gateway has built-in multiple routing filters, which are generated by the factory class of gatewayfilter.
There are generally only two types of filters:

GatewayFilter
GlobalFilter

Custom global filter
There are too many filters, so it’s very troublesome to learn. Here is a user-defined filter. For example, it’s more general. If necessary, you can configure it yourself:
To create a package filter, and then create a filter class, you need to implement two interfaces: globalfilter and ordered:
@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 is null, illegal user, O (╥﹏╥) O");
        exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
        return exchange.getResponse().setComplete();
    }

    return chain.filter(exchange);
}

@Override
public int getOrder()
{
    return 0;
}

}

Recommended Today

Client cannot authenticate XXX:[TOKEN, KERBEROS]

Caused by: org.apache.hadoop.security.AccessControlException: Client cannot authenticate xxx:[TOKEN, KERBEROS] The security authentication failed. The causes are as follows:1. Check whether the Kerberos address can be connected normally //IP of KDC System.setProperty(“java.security.krb5.kdc”, “192.168.1.1”); // realm System.setProperty(“java.security.krb5.realm”, “XXX”); 2. The configuration file could not be read successfully UserGroupInformation. Loginuserfromkeytab (user name, path of KeyTab file); It is recommended […]