Moment For Technology

Spring Cloud Gateway Predict

Posted on Dec. 3, 2022, 9:03 a.m. by 馬雅惠
Category: The back-end Tag: The back-end spring curl Regular expressions

Spring Cloud Gateway workflow

In the initial experience of Spring Cloud Gateway in the previous article, you have a preliminary understanding of the functions of Spring Cloud Gateway. As an entrance to the traffic of a system, the Gateway plays an important role, which is usually as follows:

  • Protocol translation, routing and forwarding
  • Aggregates traffic, monitors traffic, and outputs logs
  • As a front-end engineering of the entire system, the flow of control, the role of limited flow
  • As the front-end boundary of the system, external traffic can only access the system through the gateway
  • Permission can be determined at the gateway layer
  • Caching can be done at the gateway layer

As the second generation Gateway of Spring Cloud framework, Spring Cloud Gateway is more powerful and has better performance than Zuul. As Spring Cloud releases, there is an official intention to abandon Zuul. In the author called the use and function of Spring Cloud Gateway, the cost of Spring Cloud Gateway to replace Zuul is very low, almost seamless switching. Spring Cloud Gateway includes almost all of Zuul's features.

Note: This picture is from the official website

As shown in the figure above, the client makes a request to the Spring Cloud Gateway. If the Gateway Handler Mapping determines that the request matches the route (predicate is used in this case), it is sent to the Gateway Web Handler for processing. The Gateway Web Handler processes requests through a chain of filters. The reason the filter chain is divided by a dotted line is that the filter chain can perform the filtering logic before or after sending the proxy request. All the "pre" filter logic is executed and then the proxy request is made. After the proxy request is made, the "POST" filter logic is executed upon receiving the response from the proxy service. This is very similar to zuul's process. When all the pre filter logic is executed, functions such as authentication, traffic limiting, log output, request header change, and protocol conversion are performed. After forwarding and receiving the response, all the logic of the "POST" filter is executed, where the response data can be modified, such as the response header, protocol transformation, and so on.

An important aspect of this process is the matching of requests and routes. In this case, predicate is used, which determines which route a request goes to.

Introduction of predicate

Predicate comes from java8 interfaces. Predicate takes an input parameter and returns a Boolean result. The interface contains various default methods to group the predicates into other complex logic (such as and, or, and not). It can be used for interface request parameter verification and to determine whether the old and new data changes and needs to be updated. Add -- with, or-- or-- negate-- not.

Spring Cloud Gateway built many Predict, the Predict source in org. Springframework. Cloud. Gateway. Handler. The predicate in the package, if readers are interested in can be read. Now list the various predicates as follows:

Note: Pictures from the Internet

In the figure above, There are many types of Predicate, such as time type Predicated (AfterRoutePredicateFactory BeforeRoutePredicateFactory BetweenRoutePredicateFactory), When only the requests that meet the requirements of a certain time are entered into the predicate and sent to the Router for processing. Type of cookie CookieRoutePredicateFactory, specify the cookies to satisfy a regular match, will enter the router; Predicate of host, Method, PATH, Querparam, and RemoteAddr. Each predicate determines whether the current client request meets the requirements. If yes, the request is processed by the current client. If there are multiple predicates, and a request satisfies multiple predicates, the first one takes effect in the order of configuration.

Predicate of actual combat

Now, predicate will be explained in the form of cases. The cases in this article are basically from the official documents, and the official document address is: http://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.0.0.RELEASE/single/spring-cloud-gateway.html; If you have any questions, please let me know and discuss with me.

Create a project and import the Spring Cloud Gateway in the project POM file to start with the spring-cloud-starter- Gateway, spring Cloud version and Spring Boot version, code as follows:

parent groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-parent/artifactId version2.0.5. /version /parent dependencyManagement dependencies dependencies groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-dependencies/artifactId versionFinchley.SR1/version typepom/type scopeimport/scope /dependency /dependencies /dependencyManagement dependency groupIdorg.springframework.cloud/groupId artifactIdspring-cloud-starter-gateway/artifactId /dependencyCopy the code

After Route Predicate Factory

AfterRoutePredicateFactory, configurable, a time when the request of the time in the configuration of time, only the hands of the router. Otherwise, an error is reported and the route is not passed.

The application. Yml configuration in the project is as follows:

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 another configuration file in application.yml, with syntax of three lines, and configure the file name by spring.profiles, which is the same as spring.profiles. Active. Then configure spring cloud gateway related configuration, configuration is the router id, id tags for every router needs a unique id, where uri are configured to route requests, this case all routed to http://httpbin.org:80/get.

Predicates: After=2017-01-20T17:42:47.789-07:00[America/Denver] Args = 2017-01-20 T17:42:47. 789-07:00 America/Denver). Here it is important to note the predicates After this configuration, follow the contract is greater than the thought of configuration, its actual processing by AfterRoutePredicateFactory this class, This After is to specify its Gateway web AfterRoutePredicateFactory handler class, in the same way, other types of predicate also follow this rule.

After the time of requests in this configuration, the request will be routed to http://httpbin.org:80/get.

Start the project, on the browser to visit http://localhost:8081/, shows http://httpbin.org:80/get returns as a result, the uri of the gateway router to configure and now. If we set the configured time after the current time, the browser will display a 404, which proves that there is no route to the configured URI.

Predicates can also be related to time, such as Before Route Predicate Factory and Between Route Predicate Factory. Readers can refer to the official documents by themselves.

Header Route Predicate Factory

Header Route Predicate Factory takes two arguments, one is the name of the Header, and the other is the value of the Header, which can be a regular expression. When this assertion matches the request header name and value, the assertion passes into the router's rule.

Add the following configuration to the project configuration file:

spring:
  profiles:
    active: header_route

---
spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: http://httpbin.org:80/get
        predicates:
        - Header=X-Request-Id, \d+
  profiles: header_route


Copy the code

In the above configuration, if the Request Header contains the x-request-id Header and the Header value is a number, the Request will be routed to the configured URI. Using curl, run the following command:

$ curl -H 'X-Request-Id:1' localhost:8081

Copy the code

After the command is executed, the correct request result is returned, but the result is omitted. If the x-request-id header is not included in the Request and the value is not a number, the Request will report 404 and the route will not be forwarded correctly.

Cookie Route Predicate Factory takes two parameters, one is the Cookie name, and the other is a value, which can be a regular expression. It is used to match a cookie with that name in a request and a request where the cookie matches a regular expression.

Add the following configuration to the configuration file:

spring:
  profiles:
    active: cookie_route


---
spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: http://httpbin.org:80/get
        predicates:
        - Cookie=name, forezp
  profiles: cookie_route

Copy the code

In the above configuration, the request with a cookie called name, cookie value for forezp request will be forwarded to the uri address is http://httpbin.org:80/get. Using the curl command to make a request with a cookie will return the correct result. Otherwise, the request will report a 404 error.

$ curl -H 'Cookie:name=forezp' localhost:8081

Copy the code

Host Route Predicate Factory

The Host Route Predicate Factory takes a parameter called hostname, which can use. * to match the Host. This parameter matches the value of host in the request header, and if it does, the request is forwarded correctly.

In the project configuration file, add the following configuration:

spring:
  profiles:
    active: host_route
---
spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: http://httpbin.org:80/get
        predicates:
        - Host=**.fangzhipeng.com
  profiles: host_route
Copy the code

In the above configuration, requests with Host fangzhipeng.com in the request header will be routed to the configured URI. Start the project, execute the following curl command, and the request will return the correct result:

curl -H 'Host:www.fangzhipeng.com' localhost:8081

Copy the code

Method Route Predicate Factory

Method Route Predicate Factory takes a parameter, which is the type of the request. For example, GET requests are forwarded to this route. Add the following configuration to the project configuration file:

spring:
  profiles:
    active: method_route

---
spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: http://httpbin.org:80/get
        predicates:
        - Method=GET
  profiles: method_route


Copy the code

In the above configuration, all GET requests are routed to the configured URI. Using the curl command to simulate a GET request, you will get the correct response.

$ curl localhost:8081

Copy the code

Using the curl command to simulate a POST request returns a 404 result.

$ curl -XPOST localhost:8081

Copy the code

Path Route Predicate Factory

The Path Route Predicate Factory takes one argument: a SPEL expression that applies the matching Path.

In the project configuration file application.yml, do the following:

spring:
  profiles:
    active: path_route
---
spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: http://httpbin.org:80/get
        predicates:
        - Path=/foo/{segment}
  profiles: path_route

Copy the code

In the above configuration, all requests that meet /foo/{segment} will be matched and routed, such as /foo/1, /foo/bar, will be matched and forwarded successfully.

Use curl to simulate a request localhost:8081/foo/dew and return the correct request result.

$ curl localhost:8081/foo/dew

Copy the code

Query Route Predicate Factory

Query Route Predicate Factory requires two parameters: a regular expression for the parameter name and the parameter value. Do the following in the project configuration file application.yml:

spring:
  profiles:
    active: query_route
---
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: http://httpbin.org:80/get
        predicates:
        - Query=foo, ba.
  profiles: query_route

Copy the code

In the above configuration file, if the request contains parameter foo and the value of foo matches ba., the request matches the route. For example, if the request contains parameter foo and the value of bar, the request can be correctly routed and forwarded.

The command to simulate the request is as follows:

$ curl localhost:8081? foo=barCopy the code

Query Route Predicate Factory can also contain only one parameter. If one parameter is specified, only the parameter name is matched. That is, if the parameters of the request contain the configured parameter name, the Route is matched. Such as the following configuration, the configuration parameters of the request parameters contain called foo will be forwarding the request to the uri is http://httpbin.org:80/get.

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: http://httpbin.org:80/get
        predicates:
        - Query=foo
  profiles: query_route

Copy the code

conclusion

In this article, we first introduced the workflow and principles of Spring Cloud Gateway, then introduced the Gateway framework built into predict and its classification, and finally highlighted several important predicts using case studies. As an assertion, Predict determines which router the request will be routed to. After the assertion, the request is entered into the logic of the Filter filter, which the next article will cover in relation to Spring Cloud Gateway filters.

The resources

http://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.0.0.RELEASE/single/spring-cloud-gateway.html

https://www.jianshu.com/p/35b60946b8ce

https://www.jianshu.com/p/03d42105f81f

Download the source code

https://github.com/forezp/SpringCloudLearning/tree/master/sc-f-gateway-predicate


Welcome to follow my public account



Scan code to pay attention to the public number has a surprise

(Please note the author and source of the article on the blog of Fang Zhipeng)

This article is [original] article, reprint please indicate the source.

This paper links: https://www.fangzhipeng.com/springcloud/2018/12/05/sc-f-gateway2/

This article from the Fang Zhipeng's blog

    Search
    About
    mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.