Detailed explanation of the use of gateway assertions

The background of gateway, why use gateway?

A system will be split into multiple microservices. How does a client call so many microservices? If there is no gateway, you can only record the address of each microservice on the client and then call it separately.
For example, as shown below:
Please add image description
Such an architecture will have many problems:
·Each business will need authentication, current limiting, permission verification, cross-domain and other logic. If each business fights independently, it will have to build its own wheel to implement it. , it can be completely extracted and put into a unified place to do it.
·If the business volume is relatively simple, this method will not cause any problems in the early stage. However, as the business becomes more and more complex, for example, opening a page on Taobao and Amazon may involve hundreds of microservices working together. If each microservice If all services are assigned a domain name, on the one hand, the client code will be difficult to maintain, involving hundreds of domain names. On the other hand, there will be a bottleneck in the number of connections. Through packet capture, it is found that hundreds of remote calls are involved, which is not possible under the mobile terminal. It will appear very inefficient.
If you need to reconstruct microservices later, it will become very troublesome. You need the client to cooperate with you in the transformation, such as commodity services. As the business becomes more and more complex, it will need to be split into multiple microservices later. Services. At this time,
the services provided to the outside world also need to be split into multiple services, and the client needs to cooperate with you in the transformation.

What is a gateway

The so-called API gateway refers to the unified entrance of the system. It encapsulates the internal structure of the application and provides unified services to the client. Some public logic that has nothing to do with the business itself can be implemented here, such as authentication, authentication, and monitoring. , routing and forwarding, etc.
After adding the AP gateway, the system architecture diagram becomes as follows:
Please add image description

Benefits brought by gateway

Insert image description here
The gateway serves as the entry point for traffic. Commonly used functions include routing and forwarding, permission verification, current limiting, etc.
Spring Cloud Gateway is the second generation gateway framework officially launched by Spring Cloud and is positioned to replace Netflix Zuul1.O. Compared with Zuul, Spring Cloud Gateway provides better performance and more powerful functions.
Spring Cloud Gateway is a responsive API gateway implemented by WebFlux+Ney+Reactor. It cannot work in a traditional servlet container, nor can it be built into a war package.
Spring Cloud Gateway aims to provide a simple and effective API routing management method for microservice architecture, and provides basic functions of the gateway based on the Filter method, such as Talk about security certification, monitoring, current limiting, etc.

Functional features

1. Built based on Spring Framework 5, Project Reactor and Spring Boot 2.0;
2. Dynamic routing: able to match any request attributes:
3. Support path rewriting;
4. Integrate Spring Cloud service discovery function (Nacos, Eruka);
5. The flow control downgrade function can be integrated (Sentinel, .Hystrix);
6. You can specify easy-to-write Predicates and Filters for routes; ## How gateway implements forwarding

Dependencies used by gateway in the project

Dependencies used in parent pom:

<properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring-cloud.version>Hoxton.SR12</spring-cloud.version>
        <spring-cloud-alibaba.version>2.2.8.RELEASE</spring-cloud-alibaba.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.12.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
<!-- springcloud的版本依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${
    
    spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${
    
    spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Dependencies used by gateway module

    <dependencies>
<!--        gateway依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

    </dependencies>

gateway's application.yml configuration information

server:
  port: 8088
spring:
  main:
    web-application-type: reactive
  application:
    name: gateway
# gateway的配置
  cloud:
    gateway:
      #路由规则
      routes: #路由,数组[这里可以放置多个路由]
        #评分管理模块网关路由配置
        - id: shop_router #当前路由标识-要求唯一,默认是UUID;
          uri: http://localhost:8089 #请求最终要被转发的地址;
          order: 1 #路由的优先级——数字越小,代表路由的优先级越高
          predicates: #断言:(条件判断——转发请求要满足的条件)
#            - Path=/shop/** #当请求路径满族path指定的规则时,此路由信息才会正常转发;
#          filters: #过滤器,是在请求传递过程中对请求做一些手脚;
#            - StripPrefix=1 #在请求转发之前去掉一层路径
            - Path=/TestController/**
            - After=2019-12-31T23:59:59.789+08:00[Asia/Shanghai]
            - CheckAuth=gys

what is assertion

Spring Cloud Gateway (Gateway for short) supports the assertion Predicate function, which is implemented based on Spring WebFlux's HandlerMapping. Gateway contains many routing assertion factories, and these factories handle many attributes of HTTP requests. When the client makes an HTTP request, HandlerMapping will obtain the request parameters and compare them with the Predicates configured in Gateway. If the rules are met, Routing is allowed according to the rules, otherwise access is denied or a 404 error is reported.

assertion classification

Official website address

built-in

The Path and After configured under the assertion tag in the configuration file are all built-in assertions, which are the assertions provided by the gateway itself. For
example:
an assertion factory based on the Datatime type.
This type of assertion makes judgments based on time. There are three main types:
AfterRoutePredicateFactory: Receive A date parameter to determine whether the requested date is later than the specified date.
BeforeRoutePredicateFactory: Receives a date parameter to determine whether the requested date is earlier than the specified date.
BetweenRoutePredicateFactory: Receives two date parameters to determine whether the requested date is within the specified time period.

customize

A custom route assertion factory needs to inherit the AbstractRoutePredicateFactory class and rewrite the logic of the apply method. In the apply method, you can get the ServerHttpRequest object through exchange...getRequest(), so that you can get the request parameters, request method, request header and other information.

Note:
1. Must be a spring component (must be a bean)
2. The class must be ended with RoutePredicateFactory (convention is greater than configuration)
3. Must inherit AbstractRoutePredicateFactory
4. Must declare a static inner class (config) declaration attribute to receive the corresponding configuration file assertion information

Return the input content information through the shoutcutFieldOrder collection

5. It needs to be combined with shortcutFieldOrderi for binding
6. Use apply to logically judge whether tue is a successful match or false if the match fails.

Example

@Component
public class CheckAuthRoutePredicateFactorya extends AbstractRoutePredicateFactory<CheckAuthRoutePredicateFactorya.Config> {
    
    


    public CheckAuthRoutePredicateFactorya() {
    
    
        super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
    
    
        return Arrays.asList("name");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
    
    
        return new GatewayPredicate() {
    
    
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
    
    
                if (config.getName().equals("gys")){
    
    
                    return true;
                }
                return false;
            }
        };
    }


    /**
 * @description: 用于接收配置文件中断言的信息
 * @author: 
 * @date: 2023/9/19 19:52
 * @param:
 * @return:
 **/
    @Validated
    public static class Config {
    
    
        private String name;
        public String getName() {
    
    
            return name;
        }

        public void setName(String name) {
    
    
            this.name = name;
        }
    }
}

The difference between assertions and filters

1. Different functions: Assertions are used to match certain conditions of the request, such as request paths, request headers, request parameters, etc., which determine whether the request should be routed to a specific target service. Filters are used to process and transform requests, such as adding request headers, modifying request bodies, recording logs, implementing authentication and authorization, etc.
2. The working principle is different: Assertions are usually used in the routing stage to match when receiving a request. If the match is successful, the request is routed to the corresponding target service. Filters are applied before or after request routing and are used to pre-process or post-process the request. It will not affect the selection of routes.
3. Different usage scenarios: Assertions are usually used for routing based on certain attributes of the request, so it is closer to the underlying implementation of the gateway. Filters are more flexible and can be used to implement business logic, such as authentication and authorization, request retry, flow control, etc.

Guess you like

Origin blog.csdn.net/weixin_45309155/article/details/133121405