1. Introduction to Spring Cloud Gateway

Spring Cloud Gateway provides API Gateway support for SpringBoot applications and has powerful intelligent routing and filter functions. This article will introduce its usage in detail. SpringCloud Gateway is a new Gateway framework for SpringCloud, which offers significant improvements in functionality and performance over the previous generation Zuul. Zuul1.x uses blocking multithreading, that is, one thread processes one connection request. The performance is poor under high concurrency conditions. Even though Zuul2.x does not block, it looks like Zuul will be abandoned in the face of continuous hops. In its place is Spring Cloud Gateway, which is based on Webflux, a non-blocking asynchronous framework with significant performance improvements and all of Zuul’s capabilities, You can switch seamlessly from Zuul to Spring Cloud Gateway. Spring Cloud Gateway is an API Gateway service built on top of the Spring ecosystem, based on Spring 5, Spring Boot 2, and Project Reactor technologies. Gateway is designed to provide a simple and efficient way to route apis, as well as powerful filter features such as fuses, traffic limiting, retry, and so on.

1.1 Related Features

The Spring Cloud Gateway has the following features:

  • It is constructed based on Spring Framework 5, Project Reactor and Spring Boot 2.0.
  • Dynamic routing: can match any request attribute;
  • You can specify Predicate and Filter for a route;
  • Integrated Circuit breaker function of Hystrix;
  • Integrate Spring Cloud service discovery;
  • Easy to write Predicate and Filter;
  • Request traffic limiting function;
  • Path rewriting is supported.

1.2 Related Concepts

  • Route: A Route is the basic building block of a gateway. It consists of an ID, a target URI, a set of assertions, and filters that match the Route if the assertion is true.
  • Predicate: Refers to the Function Predicate of Java 8. The input type is ServerWebExchange in the Spring framework. This allows developers to match everything in an HTTP request, such as request headers or request parameters. If the request matches the assertion, it is routed;
  • Filter: Refers to an instance of GatewayFilter in the Spring framework, which allows you to modify requests before and after they are routed.

2. Create the Spring Cloud Gateway project

2.1 Adding related dependencies to poM

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-cloud-demo</artifactId>
        <groupId>com.hxmec</groupId>
        <version>1.0 the SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-cloud-gateway</artifactId>

    <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>
        <! -- Use Eureka registry -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <! -- SpringCloud Hystrix Microservices fault tolerant monitoring components: circuit breakers, dependency isolation, service degradation, service monitoring dependencies -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <! -- Health check -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
Copy the code

Create the startup class GateWayApplication, the startup class code is as follows:

@SpringBootApplication
@EnableDiscoveryClient
public class GateWayApplication {

    public static void main(String[] args) { SpringApplication.run(GateWayApplication.class, args); }}Copy the code

2.2 There are two ways to configure the Spring Cloud Gateway route

  • Configuration file Mode
  • Java Bean way

2.2.1 Configuration file Mode

Add the configuration file bootstrap.yml as follows:

server:
  port: 9100
eureka:
  instance:
    # Send heartbeat every 5s
    lease-renewal-interval-in-seconds: 5
    Notify the server that it does not receive a heartbeat within 10 seconds to remove the service from the list
    lease-expiration-duration-in-seconds: 10
    # Health check path
    health-check-url-path: /actuator/health
  client:
    The default is 30 seconds
    registry-fetch-interval-seconds: 5
    serviceUrl:
      # Eureka Registry address
      defaultZone: http://localhost:8888/eureka/
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      discovery:
        locator:
          # enable dynamic route creation from registry
          enabled: true
          Use lowercase service names. Default is uppercase
          lower-case-service-id: true
      routes:
        - id: eureka-client-provider # Route ID
          uri: lb://eureka-client-provider
          predicates:
            - Path=/provider/** # Routing rules
          filters:
            - StripPrefix=1
        - id: eureka-client-consumer # Route ID
          uri: lb://eureka-client-consumer
          predicates:
            - Path=/consumer/** # Routing rules
          filters:
            - StripPrefix=1
Copy the code

2.2.2 The JAVA BEAN configuration is as follows

Add a JAVA class, GatewayConfig, to configure routing

@Configuration
public class GatewayConfig {

    @Bean
    public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes ()
                .route (r -> r.path ("/provider/**")
                        .filters (f -> f.stripPrefix (1))
                        .uri ("lb://eureka-client-provider")
                        .id ("eureka-client-provider")
                )
                .route (r -> r.path ("/consumer/**")
                        .filters (f -> f.stripPrefix (1))
                        .uri ("lb://eureka-client-consumer")
                        .id ("eureka-client-consumer") ) .build (); }}Copy the code

2.3 Start the program and test the route

Start spring-Cloud-Eureka-Server, spring-Cloud-Eureka-client-provider, spring-Cloud-Eureka-client-consumer, and spring created in this article – the cloud – gateway project. The test address is as follows:

  • http://localhost:9100/provider/demo/hello
  • http://localhost:9100/consumer/test/callHello

    The request address indicates that the request has been routed to the corresponding service.

3. Project Git address

Making github.com/ty197287300…

4. Reference

  • Cloud.spring. IO /spring-clou…