• Lambda expressions – Nuggets (juejin. Cn)
  • Java 8 Stream – Juejin
  • WebFlux first Experience – Nuggets (juejin. Cn)

Now that you’ve covered the basics, it’s finally time to learn about the Spring Cloud Gateway.

Spring Cloud Gateway is a Gateway developed based on Spring 5.0, Spring Boot 2.0 and Project Reactor technologies. So there is the pre-knowledge of WebFlux, which in turn requires Stream streams and Lambda expressions as pre-knowledge.

Starting with this article, you will begin the technical study of the microservices series.

Without further ado, let’s begin today’s lesson.

introduce

Spring Cloud Gateway

The Spring Cloud Gateway is an API Gateway built on top of the Spring ecosystem, including Spring 5.x, Spring Boot 2.x, and Project Reactor. It aims to provide a simple and effective unified API route management approach for microservices architecture.

What is a service gateway

The API Gateway (APIGW/API Gateway), as the name implies, is the only entry to the system. The API gateway encapsulates the internal architecture of the system and provides customized apis for each client. In recent years, the demand for connectivity between mobile applications and enterprises has risen. From a single Web application to a variety of scenarios, each of which has different requirements for background services. This not only increases the response volume of the backend service, but also increases the complexity of the backend service. With the introduction of the concept of microservices architecture, API gateway has become a standard component of microservices architecture.

Why use a gateway

Microservices may be deployed in different computer rooms, regions, and domain names. When the client (browser/mobile phone/software tool) wants to request the corresponding service, it needs to know the specific IP or domain name URL of the machine. When there are many micro-service instances, it is very difficult to remember, and it is also too complex for the client to maintain. At this point, there is a gateway. The client-related requests are directly sent to the gateway, which determines the specific micro-service address according to the request identification and then forwards the request to the micro-service instance. The memory function is all handed over to the gateway to operate.

The working process

The client makes a request to the Spring Cloud Gateway. If a route matching the request is found in the Gateway Handler Mapping, it is sent to the Gateway Web Handler. The Handler then sends the request through the specified filter chain (chain of Responsibility design pattern) to our actual service to perform the business logic, and then returns.

Characteristics of the

Characteristics of SpringCloud Gateway are as follows:

  1. Based on Spring Framework 5, Project Reactor and Spring Boot 2.0
  2. Integrated Hystrix circuit breaker
  3. Integrate with Spring Cloud DiscoveryClient
  4. Predicates and Filters are easy to write for specific routes
  5. Advanced gateway functions include dynamic routing, traffic limiting, and path rewriting
  6. The path to rewrite
  7. Current limiting
  8. Dynamic routing

The core concept

  • RouteA route is the most basic part of a gateway, 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 function in Java8. The assertion function input type in the Spring Cloud Gateway is ServerWebExchange from the Spring 5.0 framework. The assertion function in the Spring Cloud Gateway allows developers to define and match any information from the Http Request, such as Request headers and parameters.
  • Filter: a standard Spring Web Filter. The filters in Spring Cloud Gateway are divided into two types, Gateway Filter and Global Filter. The filter will process the request and response.

Learn to use

Create a Spring Boot project directly in idea:

The Spring Cloud Gateway dependency is automatically introduced in the POM.xml file:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </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>
Copy the code

Application. Yml configuration file:

server: port: 8080 spring: application: name: api-gateway cloud: gateway: routes: - id: cloud-gateway uri: http://192.168.1.211:8088/ predicates: - Path = / ytb / * *Copy the code

The meanings of the parameters are as follows:

  • Id: indicates the user-defined route ID, which must be unique
  • Uri: indicates the address of the target service
  • Predicates: Routing conditions. 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).
  • Filters: filter rules that are not used here.

A URI proxy rule with the ID of cloud-gateway is configured. The routing rule is as follows:

When access the address http://localhost:8080/ytb/fileType/getFileTypeList, http://192.168.1.211:8088/ytb/fileType/getFileTypeList will be automatically forwarded to the address

The address forwarded to is one of my test addresses returned as follows:

In addition to the application.yml configuration, forwarding can also be implemented in code. We can customize the forwarding rules by adding the customRouteLocator() method to the GateWayApplication startup class.

@SpringBootApplication
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder){
        return builder.routes()
                .route("path_route", r -> r.path("/ytb/**").uri("http://192.168.1.211:8088/")).build(); }}Copy the code

So this is where we use functional programming that we learned before. Start the project visit http://localhost:8080/ytb/fileType/getFileTypeList address, we will be the same as the above return the result.

Routing rules

Spring Cloud Gateway uses HandlerMapping of Spring WebFlux as the underlying support to match forward routes. Spring Cloud Gateway has many built-in Predicates factories. These Predicates factories are matched by different HTTP request parameters, and multiple Predicates factories can be combined.

Predicate comes from Java 8. It’s a function introduced in Java 8. 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.

Let’s take a look at the specific routing rules.

Datetime

Matches requests that occur after date and time

spring: 
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: http://localhost:9201/
          predicates:
            - After = 2021-02-23 T14:20:00. 000 + 08:00 Asia/Shanghai
Copy the code

Cookie

Matches cookies whose names are specified and whose values match the regular expression

spring: 
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: http://localhost:9201/
          predicates:
            - Cookie=username, ezhang
Copy the code

Header

Matches the request header with the specified name, and the \d+ value matches the regular expression

spring: 
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: http://localhost:9201/
          predicates:
            - Header=X-Request-Id, \d+
Copy the code

Host

A list of matching host names

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-gateway
          uri: https://www.baidu.com
          predicates:
            - Host=**.baidu.com
Copy the code

Curl curl curl curl curl curl curl

curl http://localhost:8080 -H “Host: www.baidu.com”

Method

Match the parameters of the request methods, which are one or more parameters

spring: 
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: http://localhost:9201/
          predicates:
            - Method=GET,POST
Copy the code

Path

Match request path

spring: 
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: http://localhost:9201/
          predicates:
            - Path=/system/**
Copy the code

This is the match request path used in the beginning.

Query

Matching query parameters

spring: 
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: http://localhost:9201/
          predicates:
            - Query=username, ezhang.
Copy the code

RemoteAddr

Matches the IP address and subnet mask

spring: 
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: http://localhost:9201/
          predicates:
            - RemoteAddr = 192.168.0.1
Copy the code

Weight

Match the weight

spring: 
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: cloud-ytb-v1
          uri: http://localhost:9201/
          predicates:
            - Weight=group1, 8
        - id: cloud-ytb-v2
          uri: http://localhost:9201/
          predicates:
            - Weight=group1, 2
Copy the code

When developing or testing, or releasing online services for multi-version control, it is necessary to provide weighted routing for services. The most common use is that a service has two versions, the old version V1 and the new version V2. When the gray scale is online, the routing weight information needs to be dynamically pushed in real time through the gateway. For example, 80% of the traffic goes to v1 and 20% to V2.

The routing configuration

There are three ways to configure urIs in the Spring Cloud Gateway, including

  • Websocket configuration mode
spring:
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: ws://localhost:9213/
          predicates:
            - Path=/ytb/**
Copy the code
  • HTTP address configuration mode
spring:
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: http://localhost:9213/
          predicates:
            - Path=/ytb/**
Copy the code
  • Registry configuration mode

The schema protocol part of the URI is a custom LB: type that subscribes to the service from a microservice registry (such as Nacos) and routes the service.

spring:
  cloud:
    gateway:
      routes:
        - id: cloud-ytb
          uri: lb://cloud-ytb
          predicates:
            - Path=/ytb/**
Copy the code

Spring Cloud Gateway and Zuul

Spring-cloud-gateway is a sub-project of Spring-Cloud. Zuul is a Netflix project, but Spring integrates Zuul with Spring-Cloud.

The Gateway project was created by the Spring team because zuul2.0 and Zuul1 were performing poorly.

Spring Cloud Gateway and Zuul:

  • Both are Web gateways that process HTTP requests.
  • Gateway relies more on Spring-webFlux than Zuul. With the support of Spring, gateway has more powerful functions. It realizes internal flow limiting and load balancing, and has stronger expansibility. Traffic limiting and load balancing are not implemented internally.
  • Gateway supports asynchro well, whereas Zuul only supports synchronization, so in theory Gateway is better suited for improving system throughput (but not necessarily performance), which will be determined by rigorous pressure testing.
  • From a framework design point of view, Gateway is more scalable and has a 2.0.0 RELESE release, which is very stable.

In general, the Spring Cloud Gateway has an advantage over the microservices architecture if it uses the basic components of the Spring Cloud ecosystem. Streaming programming + asynchronous support alone is enough to make it a choice for developers.

Zuul is also a good choice for small microservice architectures or complex architectures that include not only microservice applications but also other non-Spring Cloud service nodes.

Note:

Spring Cloud Gateway needs Netty provided by SpringBoot and SpringWebFlux to run. It cannot be run in Tomcat as a WAR package. Therefore, there is no need to add spring-boot-starter-Web dependencies in the project.

Spring Cloud Gateway