Reference: blog.csdn.net/forezp/arti…

The paper

Gateway, as the gateway, is the first wall for external access and also the entrance of the flow of the whole system. Its functions are as follows:

  • Protocol translation and route forwarding
  • Traffic aggregation: Monitors traffic and generates logs
  • As the front-end engineering of the whole system, the flow control, the role of limited flow
  • As the front-end boundary of the system, external traffic can access the system only through the gateway
  • Permissions can be determined at the gateway layer
  • Caching can be done at the gateway layer

The client makes a request to the SpringCloud Gateway, and if the Gateway Handler Mapping determines that the request matches the route, it is sent to the Gateway Web Handler for processing, which then passes through a chain of filters to make the proxy request. After issuing the proxy request, the “POST” filter logic is performed upon receiving the response from the proxy service. This is similar to zuul’s process. During the implementation of all pre filter logic, functions such as authentication, traffic limiting, log output, request header change, and protocol conversion are often carried out. After receiving the response after forwarding, all the logic of the “POST” filter is performed, where the response data can be modified, such as the response header, protocol transformation, and so on.

There’s an important point in the process of matching requests and routes, and you need predicate, which determines which route a request goes through.

Introduction of predicate

Predicate comes from the Java8 interface. Predicate takes an input parameter and returns a Boolean result. This interface contains default methods for grouping Predicate into other complex logic (such as and, or, or not). It can be used to verify interface request parameters and determine whether new and old data is changed and needs to be updated. Add — with, or — or, negate — not.

server: port: 8081 spring: profiles: active: after_route --- spring: cloud: gateway: routes: - id: after_route uri: http://httpbin.org:80/get predicates: T17 - After = 2017-01-20:42:47. 789 - from America/Denver profiles: after_routeCopy the code

In the above configuration file, configure the service port 8081, configure spring. Profiles. Active: after_route spring’s boot file specifies the program for after_route file. Create a new configuration file in application.yml with the syntax of three lines. In this configuration file, use spring.profiles to configure the file name, same as spring.profiles. The ID tag configures the ID of the router, each router needs a unique ID, and the URI configures where requests are routed.

The predicates are located between the Gateway Client and Gateway Handler Mapping. For example, the above code is at the time 2017-01-20…. Subsequent requests are forwarded to the specified URI. Many complex judgments are supported in Predicates, as you can see in the reference article at the beginning.

Introduction of the filter

Function and lifecycle of filter

From the filter workflow point, it can be seen that filter plays a very important role. Filter of “Pre” type can be used for parameter verification, permission verification, traffic monitoring, log output, protocol conversion, etc. Filter of “POST” type can be used for response content, response header modification, log output, traffic monitoring, etc. First of all, we need to make clear why the gateway layer is needed, and then we have to talk about the role of filter.

role

When we have multiple services, such as user-service, goods-service, and sales-service in the figure below, when the client requests the Api of each service, each service needs to do the same things, such as authentication, traffic limiting, and log output.Is there a way to do this repetitive work better? The answer is yes. Add an Api Gatewat service with global permission control, traffic limiting and log output on the top layer of the microservice, and then forward the request to the specific business service layer. The Api Gateway service acts as a service boundary, and external requests to access the system must first pass through the Gateway layer.

The life cycle

Spring Cloud Gateway is similar to Zuul in that it has “Pre” and “post” filters. The request from the client passes the Pre filter and is forwarded to a specific service, such as user-service in the figure above. After receiving the response from the service, the request is processed by the Post filter and sent to the client.

Custom filter

There are 19 filters built into the Spring Cloud Gateway, but you can customize your own

public class RequestTimeFilter implements GatewayFilter, Ordered { private static final Log log = LogFactory.getLog(GatewayFilter.class); private static final String REQUEST_TIME_BEGIN = "requestTimeBegin"; Public static final List<String> NOT_INTERCEPT = new ArrayList<>(); public static final List<String> NOT_INTERCEPT = new ArrayList<>(); Static {NOT_INTERCEPT. Add ("/ API /user/login"); NOT_INTERCEPT.add("/api/v2/user/user/login"); NOT_INTERCEPT.add("/api/v2/user/dataRepair/repairRoleAuthData"); NOT_INTERCEPT.add("/api/v2/user/license/updateDocCount"); NOT_INTERCEPT.add("/api/user/signup"); NOT_INTERCEPT.add("/api/user/forget-pwd"); NOT_INTERCEPT.add("/api/user/modify-pwd"); NOT_INTERCEPT.add("/api/user/invite-info"); NOT_INTERCEPT.add("/api/company/config"); NOT_INTERCEPT.add("/api/wechat/login"); NOT_INTERCEPT.add("/api/wechat/login-redirect"); NOT_INTERCEPT.add("/api/wechat/inner/login-redirect"); NOT_INTERCEPT.add("/api/wechat/mobile-login-redirect"); NOT_INTERCEPT.add("/api/wechat/inner/mobile-login-redirect"); NOT_INTERCEPT.add("/api/chat/login-page"); NOT_INTERCEPT.add("/api/chat/to-login-page"); NOT_INTERCEPT. Add ("/ API /wechat/login-url")} @override Public Mono<Void> filter(ServerWebExchange Exchange, GatewayFilterChain chain) { exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis()); //chain. Filter Return chain.filter(exchange).then(mono.fromrunnable (() -> {Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN); if (startTime ! = null) { log.info(exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + "ms"); }})); } @override public int getOrder() {return 0; }}Copy the code

Filter-chain is connected by the values set by the getOrder method in Ordered. The smaller the value, the higher the priority.

Filter for limiting traffic

There are three common traffic limiting algorithms:

  • counter
  • Bucket algorithm
  • Token bucket algorithm

Check out these two articles:

  • www.jianshu.com/p/36bca4ed6…
  • Blog.csdn.net/forezp/arti…

Spring Cloud Gateway traffic limiting

The filters in the Spring Cloud GateWay use lua scripts to implement token bucket traffic limiting, as shown in the figure below: