SpringCloud article: GateWay gateway

Table of contents

1. What is a service gateway

2. The role of the gateway

3. Basic principles of Spring Cloud Gateway

 4. Steps to build gateway service

5. Assertion Factory

6. Filter factory

 4.1. Request header filter

4.2, the default filter (default-filters)

4.2.1. Summary

4.3. Global filter

4.3.1. Implementation

4.4, filter execution order

Collation:


1. What is a service gateway

        In the traditional monolithic architecture, only one service needs to be opened for the client to call, but in the microservice architecture, a system is split into multiple microservices. If there is no gateway, the client can only record the invocation of each microservice locally Address, when there are a large number of microservices that need to be called, it needs to understand the interface of each service, which is a lot of work. After having a gateway, how can it be improved?

     As the only traffic entrance of the system, the gateway encapsulates the architecture of the internal system. All requests go through the gateway first, and the gateway routes the request to the appropriate microservice. Therefore, the benefits of using the gateway are:  

(1) Simplify the work of the client. After the gateway encapsulates the microservices, the client only needs to interact with the gateway instead of calling different services;
(2) Reduce the coupling between functions. Once the service interface is modified, only the routing strategy of the gateway needs to be modified, and each client that calls the function does not need to be modified, thereby reducing the coupling between programs. (3) Freeing developers to focus
on the realization of business logic. Non-business-related functions such as service routing (grayscale and ABTest), load balancing, access control, and flow control fuse downgrade are implemented by the gateway in a unified manner, without the need to consider each service API when implementing it.

2. The role of the gateway

  • Request routing : forwarding requests to different microservices according to the attributes of the request itself is one of the basic functions of the microservice gateway. Business operation and maintenance personnel need to configure routes for different services, so that the gateway can forward requests to corresponding services based on attributes such as headers, paths, parameters, and protocols.
  • Service discovery : The gateway is the request entry point of the microservice environment. Supporting service discovery enables the gateway to make full use of the advantages of the service registry to dynamically manage service instances when forwarding requests to the target service, and it is also more convenient when configuring the target address for route forwarding.
  • Modify request response : Before the gateway receives an external request and forwards it to the target service, it can modify the request according to the requirements, such as changing the request header, parameters, etc. Similarly, after obtaining the business service response, the response can be modified before being returned to the user.
  • Authority verification : Some business scenarios need to verify user authority first when processing user requests, and this part of the logic can also be handled by the gateway. When the request arrives at the gateway, the gateway first authenticates the user according to the service interface to be accessed by the request. Only the request that passes the verification will be forwarded to the corresponding service, and the request that fails the verification will be directly rejected by the gateway. Doing so can advance the step of rejecting invalid requests to the gateway layer, reducing invalid traffic from entering business services.
  • Current limiting and circuit breaker : The gateway can protect business services by adding mechanisms such as current limit and circuit breaker, and improve the overall availability of the system. According to the throughput of the business service, the gateway can limit the number of requests forwarded to the service, and requests exceeding the limit are directly rejected or downgraded, which can avoid the situation that the business service load is too high due to too many requests. When the business service is abnormal, the effect of fast failure can also be achieved by fusing.
  • Request retry : For some idempotent requests, when the gateway fails to forward the target service, automatic retry can be done at the gateway layer. For some multi-instance deployment services, you can also consider forwarding the request to a different instance when retrying to improve the probability of the request being successful.
  • Response caching : When a user requests some static or infrequently updated data, the data obtained by multiple requests within a period of time is likely to be the same. In this case the response can be cached. In this way, user requests can get response data directly at the gateway layer, eliminating the need to access business services and reducing the burden on business services.
  • Response aggregation : In some cases, the response content of the user request may come from multiple business services. As the caller of business services, the gateway can integrate the responses of multiple services and return them to the user together.
  • Monitoring and statistics : Because the gateway is the request entrance, it is convenient to monitor and count external access requests at the gateway level, and at the same time monitor the response of business services to facilitate the discovery of abnormal situations.
  • Grayscale traffic : the gateway can be used for grayscale switching of service traffic. For example, if a new version of a business service is launched, a part of the request traffic can be switched to the new version of the service at the gateway level according to the grayscale strategy, so as to verify the function and performance of the new version of the business service.
  • Abnormal response processing : For the abnormal response returned by the business service, conversion processing can be performed at the gateway layer before being returned to the user. In this way, some exception details returned by the business side can be hidden and converted into user-friendly error prompts.

3. Basic principles of Spring Cloud Gateway

        Gateway itself is a Spring Boot application, and its processing logic is to preprocess and forward the request according to the configured route.

Gateway has several core concepts:

  • Route : A Route consists of routing ID, forwarding URI, multiple Predicates and multiple Filters. Multiple Routes can be configured on the Gateway. When processing requests, they will be sorted by priority, and the first Route that satisfies all Predicates will be found;
  • Predicate : Indicates the matching condition of the route, which can be used to match various attributes of the request, such as request path, method, header, etc. A Route can contain multiple sub-Predicates, and multiple sub-Predicates will eventually be merged into one;
  • Filter : The filter includes the logic for processing requests and responses, which can be divided into two stages: pre and post. Multiple Filters will be executed in order of priority from high to low in the pre phase, and the post phase will be executed in reverse. Gateway includes two types of Filter.
  1. Global Filter: There is only one instance of each global Filter, and it will take effect on all Routes.
  2. Routing Filter: Routing Filter is configured for Route, and different Routes can use different parameters, so different instances will be created.

 4. Steps to build gateway service

1. Create a new module and introduce the dependency of SpringCloudGateway and the service discovery dependency of nacos.

<!--网关依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<! --nacos服务发现依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2. Write the routing configuration, that is, the nacos address

server:
  port: 8089 # 网关端口
spring:
  application:
    name: gateway # 服务名称
  cloud:
    nacos:
      server-addr: localhost:8848 # nacos地址
    gateway:
      routes: # 网关路由配置
        - id: user-service # 路由id,自定义,只要唯一即可
          # uri: http://127.0.0.1:8081 # 路由的目标地址 http就是固定地址
          uri: lb://userservice # 路由的目标地址 lb就是负载均衡,后面跟服务名称
          predicates: # 路由断言,也就是判断请求是否符合路由规则的条件
            - Path=/user/** # 这个是按照路径匹配,只要以/user/开头就符合要求

We will proxy all requests that match the path rule to the address specified by the uri parameter.

In this example, we proxy  /user/**the initial request to, lb://userservicelb is load balancing, pull the service list according to the service name, and realize load balancing.

Routing configuration includes:

  1. Route id: the unique identifier of the route

  2. Routing destination (uri): the destination address of the routing, http stands for fixed address, lb stands for load balancing based on service name

  3. Routing assertions (predicates): rules for judging routing,

  4. Route filters (filters): process the request or response

5. Assertion Factory

Spring provides 11 basic Predicate factories:

The role of PredicateFactory:

  • Read user-defined assertion conditions and make judgments on requests

What does Path=/user/** mean?

  • If the path starts with /user, it is considered to be in compliance

6. Filter factory

GatewayFilter is a filter provided in the gateway, which can process the requests entering the gateway and the responses returned by microservices :

 Spring provides 31 different route filter factories. For example:

 4.1. Request header filter

Let's take AddRequestHeader as an example to explain.

Requirement : Add a request header to all requests entering userservice: Truth=itcast is freaking awesome!

Just modify the application.yml file of the gateway service and add route filtering:

spring:
  cloud:
    gateway:
      routes:
      - id: user-service 
        uri: lb://userservice 
        predicates: 
        - Path=/user/** 
        filters: # 过滤器
        - AddRequestHeader=Truth, Itcast is freaking awesome! # 添加请求头

 The current filter is written under the userservice route, so it is only valid for requests to access UserService.

4.2, the default filter (default-filters)

If you want to take effect for all routes, you can write the filter factory under default. The format is as follows:

spring:
  cloud:
    gateway:
      routes:
      - id: user-service 
        uri: lb://userservice 
        predicates: 
        - Path=/user/**
      default-filters: # 默认过滤项
      - AddRequestHeader=Truth, Itcast is freaking awesome!

4.2.1. Summary

The role of the filter

① Process the routing request or response, such as adding a request header

② The filter configured under the route only takes effect for the request of the current route

4.3. Global filter

Requirements : Define a global filter, intercept requests, and determine whether the parameters of the request meet the following conditions:

  • Whether there is authorization in the parameter,

  • Whether the authorization parameter value is admin

If it is satisfied at the same time, let it go, otherwise block it

4.3.1. Implementation

Define a filter in gateway :

  1. Implement the GlobalFilter interface
  2. Add @Order annotation or implement Ordered interface
  3. write processing logic
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
 
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        // 2.获取authorization参数
        String auth = params.getFirst("authorization");
        // 3.校验
        if ("admin".equals(auth)) {
            // 放行
            return chain.filter(exchange);
        }
        // 4.拦截
        // 4.1.禁止访问,设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2.结束处理
        return exchange.getResponse().setComplete();
    }
}

The role of the global filter : it is valid for all routes, and the processing logic can be customized

4.4, filter execution order

        When a request enters the gateway, it will encounter three types of filters: current route filter, DefaultFilter, GlobalFilter

        After requesting routing, the current routing filter, DefaultFilter, and GlobalFilter will be merged into a filter chain (collection), and each filter will be executed in turn after sorting:

 

Collation:

  • Each filter must specify an int type order value, the smaller the order value, the higher the priority, and the higher the execution order.
  • GlobalFilter specifies the order value by implementing the Ordered interface or adding the @Order annotation, which is specified by ourselves
  • The order of routing filters and defaultFilter is specified by Spring, and the default is to increase from 1 according to the order of declaration .
  • When the order values ​​of the filters are the same, they will be executed in the order of defaultFilter > routing filter > GlobalFilter .

Guess you like

Origin blog.csdn.net/qq_54247497/article/details/131498213