Spring Cloud Component Gateway Spring Cloud Gateway (Hoxton version)

content

1. Introduction to Spring Cloud Gateway

1.1 Related Features

1.2 Related concepts

2. Create a Spring Cloud Gateway project

2.1 Add related dependencies to pom

2.2 There are two ways to configure spring cloud gateway routing

2.2.1 Configuration file method

2.2.2 The JAVA BEAN configuration is as follows

2.3 Start the program and perform routing tests

3. Project git address

4. Reference


1. Introduction to Spring Cloud Gateway

Spring Cloud Gateway provides API gateway support for SpringBoot applications, with powerful intelligent routing and filter functions. This article will introduce its usage in detail. Spring Cloud Gateway is a new gateway framework launched by Spring Cloud. Compared with the previous generation Zuul, its functions and performance have been greatly improved. Zuul1.x uses a blocking multi-threading method, that is, one thread processes a connection request, and the performance is poor in high concurrency conditions. Even though Zuul2.x is non-blocking, it seems that Zuul needs to face continuous bounces. was abandoned. Instead, Spring Cloud Gateway, which is based on Webflux, is a non-blocking asynchronous framework with greatly improved performance, and includes all the functions of Zuul, which can be seamlessly switched from Zuul to Spring Cloud Gateway. Spring Cloud Gateway is an API gateway service built on top of the Spring ecosystem, based on technologies such as Spring 5, Spring Boot 2, and Project Reactor. Gateway aims to provide a simple and effective way to route APIs, as well as provide some powerful filter functions, such as: circuit breaker, current limit, retry, etc.

The working principle of the official website Gateway is as follows:

1.1 Related Features

Spring Cloud Gateway has the following features:

  • Built on Spring Framework 5, Project Reactor and Spring Boot 2.0;
  • Dynamic routing: can match any request attribute;
  • Predicate (assertion) and Filter (filter) can be specified for the route;
  • Integrate the circuit breaker function of Hystrix;
  • Integrate Spring Cloud service discovery function;
  • Easy-to-write Predicate and Filter;
  • Request current limiting function;
  • Path rewriting is supported.

1.2 Related concepts

  • Route (Route): Route is the basic module for building a gateway. It consists of ID, target URI, a series of assertions and filters. If the assertion is true, the route is matched;
  • Predicate: Refers to Java 8's Function Predicate. The input type is ServerWebExchange in Spring framework. This allows developers to match everything in an HTTP request, such as request headers or request parameters. Route if the request matches the assertion;
  • Filter (filter): Refers to the instance of GatewayFilter in the Spring framework. Using the filter, the request can be modified before and after the request is routed.

2. Create a Spring Cloud Gateway project

2.1 Add 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-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>
        <!--使用Eureka注册中心-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- SpringCloud Hystrix 微服务容错监控组件:断路器,依赖隔离,服务降级,服务监控 依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!-- 健康检查 -->
        <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>
复制代码

Create a 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);
    }

}
复制代码

2.2 There are two ways to configure spring cloud gateway routing

  • configuration file
  • Java Bean way

2.2.1 Configuration file method

Add the configuration file bootstrap.yml, the content is as follows:

server:
  port: 9100
eureka:
  instance:
    #每隔5s发送一次心跳
    lease-renewal-interval-in-seconds: 5
    #告知服务端10秒还未收到心跳的话,就将该服务移除列表
    lease-expiration-duration-in-seconds: 10
    #健康检查路径
    health-check-url-path: /actuator/health
  client:
    #默认为30秒
    registry-fetch-interval-seconds: 5
    serviceUrl:
      #eureka注册中心地址
      defaultZone: http://localhost:8888/eureka/
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      discovery:
        locator:
          #开启从注册中心动态创建路由的功能
          enabled: true
          #使用小写服务名,默认是大写
          lower-case-service-id: true
      routes:
        - id: eureka-client-provider #路由的ID
          uri: lb://eureka-client-provider
          predicates:
            - Path=/provider/** # 路由规则
          filters:
            - StripPrefix=1
        - id: eureka-client-consumer #路由的ID
          uri: lb://eureka-client-consumer
          predicates:
            - Path=/consumer/** # 路由规则
          filters:
            - StripPrefix=1
复制代码

2.2.2 The JAVA BEAN configuration is as follows

Add a JAVA class GatewayConfig for configuring 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 ();
    }
}
复制代码

2.3 Start the program and perform routing tests

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

http://localhost:9100/provider/demo/hello

http://localhost:9100/consumer/test/callHello

3. Project git address

GitHub https://github.com/ty1972873004/spring-cloud-demo

4. Reference

Guess you like

Origin blog.csdn.net/m0_54850467/article/details/123684873