Micro-service routing SpringCloud of GateWay

In front of the blog to learn gateway zuul, spring comes with the official gateway spring cloud gateway at school today. Zuul (1.x) based Servlet, use blocking API, which does not support any long connection, such as WebSockets, Spring Cloud Gateway to use non-blocking API, support for WebSockets, support for new features such as limiting.

Spring Cloud Gateway is a new project Spring Cloud, the project is based on the gateway technology developed by Spring 5.0, Spring Boot 2.0 and Project Reactor, etc., it aims to provide a simple and effective unified micro Services Architecture API routing management.

Spring Cloud Gateway as Spring Cloud ecosystem gateway, the goal is to replace Netflix Zuul, which not only provides a unified routing, and provides the basic functions of gateway-based approach Filter chain, such as: security, monitoring / indicators, and current limit .

Related concepts:

The Route (route): This is the basic building block of the gateway. It is defined by an ID, a target URI, a set of assertions and a set of filters. If the assertion is true, the route matches.
Predicate (assertion): This is a Java 8 of Predicate. The input type is a ServerWebExchange. We can use it to match any of the content from the HTTP request, such as headers or parameters.
Filter (filter): This is an example org.springframework.cloud.gateway.filter.GatewayFilter, we can use it to modify requests and responses.
work process:

 

The client makes a request to Spring Cloud Gateway. If the request matches found Gateway Handler Mapping the route, it sends to the Gateway Web Handler. Handler then through the specified filter chain to send a request to the service we actually execute business logic and then returns. Separated by a dashed line between the filter because the filter may be ( "pre") or after ( "post") execute business logic before sending a proxy request.

Spring Cloud Gateway features:

  1. Based on Spring Framework 5, Project Reactor and Spring Boot 2.0
  2. Dynamic Routing
  3. Predicates and Filters act on a specific route
  4. Integrated circuit breaker Hystrix
  5. 集成 Spring Cloud DiscoveryClient
  6. Filters are easy to write and Predicates
  7. Limiting
  8. Path Rewrite

Spring Cloud Gateway Gateway Routing There are two configurations, where recommended yml configuration.

  1. Configured in the configuration file in yml
  2. Custom RouteLocator, disposed in the main class Application startup by @Bean

Let's implement a simple routing forwarding demo:

1. dependence introduction

It should be the introduction of spring-cloud-starter-gateway.

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>SpringCloudGatewayDemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>SpringCloudGatewayDemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR2</spring-cloud.version>
    </properties>

    <dependencies> 
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
View Code

2. Create application.yml increase the allocation

server:
  port: 8081
spring:
  cloud:
    gateway:
      routes:
      - id: neo_route
        uri: http://www.cnblogs.com
        predicates:
          - Path=/5ishare

The fields have the following meanings:

id: ID routing our custom, remains unique
uri: target service address
predicates: routing conditions, Predicate accepts an input parameter and returns a Boolean result. The interface comprises a plurality of default methods to be combined into other complex Predicate logic (such as: and, or, not).
filters: filtering rules, this exemplary temporary useless.

This means that the above configuration, equipped with an id of routing rules neo_route when accessing the address http: address is automatically forwarded to the 8081 / 5ishare:: http: // localhost //www.cnblogs.com/spring-cloud . Configuration start the project can be tested in a browser visits when we visit the address http: // localhost: will show when the 8080 / 5ishare https://www.cnblogs.com/5ishare page.

Routing rules

Spring Cloud Gateway function is very powerful, we can be seen only through Predicates design, we just use the front of the predicates that match the criteria for a simple, in fact, Spring Cloud Gataway help us built a lot of Predicates function.

Spring Cloud Gateway is as a through Spring WebFlux HandlerMapping underlying support to match the forward route, Spring Cloud Gateway Predicates built many factories, plants Predicates these requests by different parameters to match HTTP, plant plurality Predicates can be combined.

Predicate describes
Predicate from Java 8, is a function introduced in Java 8, Predicate accepts an input parameter and returns a boolean result. The interface comprises a plurality of default methods to be combined into other complex Predicate logic (such as: and, or, not). Interface parameters may be used to verify the request, determine whether there are changes to the new and old data update operation.

In the Spring Spring Cloud Gateway Predicate achieved using various properties of the matching routing rules, there by Header, different conditions requested parameters to be matched as a condition corresponding routing. Internet has achieved a figure summarizes the Spring Cloud built of several Predicate.

 

By matching the time
Predicate support a set time, when forwarding the request may be forwarded before or after this time is determined by. Forwarding the set after use After this time, before forwarding Before setting the time, setting the Between forward end of the time interval. Does not work when the other two and then modify Between Before and after the testing process began setting After forwarding, you need to clear your browser cache at.

server:
  port: 8081
spring:
  cloud:
    gateway:
      routes:
       - id: time_route
         uri: http://www.cnblogs.com
         predicates:
          -After=2019-11-03T10:20:06+08:00[Asia/Shanghai]
#          - Before=2019-11-03T10:55:06+08:00[Asia/Shanghai]
#          - Between=2019-11-03T11:01:06+08:00[Asia/Shanghai], 2019-11-03T11:05:06+08:00[Asia/Shanghai]

By matching Cookie

 Cookie Route Predicate may receive two parameters, a Cookie name, a regular expression, regular expression routing rule to match by taking the Cookie name corresponding to the value of n and, if the matching will be executed on the route, if no match is It is not executed. It is shown below jump when added in the name = cuiyw Cookie request to http://www.cnblogs.com, when the error is not added 404 times.

By matching the Header property

Header Route Predicate 和 Cookie Route Predicate 一样,也是接收 2 个参数,一个 header 中属性名称和一个正则表达式,这个属性值和正则表达式匹配则执行。如下图所示当设置X-Request-Id=6666时页面跳转正常,当设置为cuiyw时报404错。

server:
  port: 8081
spring:
  cloud:
    gateway:
      routes:
       - id: cookie_route
         uri: http://www.cnblogs.com
         predicates:
           - Cookie=name,cuiyw
           - Header=X-Request-Id, \d+

 

 

 通过 Host 匹配

 Host Route Predicate 接收一组参数,一组匹配的域名列表,这个模板是一个 ant 分隔的模板,用.号作为分隔符。它通过参数中的主机地址作为匹配规则。这里没测试出来,暂时略过。

通过请求方式匹配

可以通过是 POST、GET、PUT、DELETE 等不同的请求方式来进行路由,如下配置文件配置的是使用Get请求来进行路由,如果使用post则报404错误

server:
  port: 8081
spring:
  cloud:
    gateway:
      routes:
       - id: method_route
         uri: http://www.cnblogs.com
         predicates:
          - Method=GET

 

通过请求路径匹配

 Path Route Predicate 接收一个匹配路径的参数来判断是否走路由。当输入http://localhost:8081/5ishare时报404错误,当输入http://localhost:8081/5ishare/p正常跳转。

server:
  port: 8081
spring:
  cloud:
    gateway:
      routes:
       - id: method_route
         uri: http://www.cnblogs.com
         predicates:
          - Method=GET
          - Path=/5ishare/{segment}

 

通过请求参数匹配

 Query Route Predicate 支持传入两个参数,一个是属性名一个为属性值,属性值可以是正则表达式。当输入http://localhost:8081/5ishare时报404错误,当输入http://localhost:8081/5ishare?name=cuiyw时跳转正常

 

 通过请求 ip 地址进行匹配

Predicate 也支持通过设置某个 ip 区间号段的请求才会路由,RemoteAddr Route Predicate 接受 cidr 符号(IPv4 或 IPv6 )字符串的列表(最小大小为1),例如 192.168.0.1/16 (其中 192.168.0.1 是 IP 地址,16 是子网掩码)。这个目前没找到验证方法,暂时略过。

组合使用

在上面的例子有就能看到多个匹配组合在一起使用。例如通过Header属性匹配中设置了Cookie和Header。

Guess you like

Origin www.cnblogs.com/5ishare/p/11785687.html