Spring Cloud Gateway content? I think it's OK

Spring Cloud Gateway is a gateway service developed on the spring official website based on Spring 5.0, Spring Boot 2.0, Project Reactor and other technologies. When we use microservices, we need to provide the basic functions of the gateway based on the Filter chain, that is, security, monitoring, current limiting and other tasks.

Spring Cloud Gateway provides a simple, effective and unified API routing management method for microservice architecture. This is the Gateway mentioned in the basic knowledge of spring cloud, that is, the Gateway.

1. Gateway gateway introduction

The core of the Spring Cloud Gateway component is a series of filters. Through these filters, we can forward (route) the requests sent by the client to the corresponding microservices.

Spring Cloud Gateway is a firewall and agent added at the forefront of the whole microservice to hide the IP port information of microservice nodes, so as to strengthen security protection.

Of course, the gateway service also needs to be registered with the Eureka registry.

2. Basic architecture of Gateway

Actually, just like the above. No matter the request from the PC or mobile terminal, or the call within the service, the request for the service needs to pass through the Gateway to realize the operation of decision or dynamic routing, etc. Among them, the Gateway is the unified entrance of our services.

3. Core concept

Based on the content of Gateway, I found three concepts on the Internet, which are included in the Gateway architecture. Next, let's take a look at the core concepts of Gateway

  • Route: consists of an ID, a destination URL, a set of assertion factories, and a set of filters. If the route assertion is true, the request URL matches the configured route.
  • Predicate the input type of the assertion function in the Spring Cloud Gateway is ServerWebExchange in the Spring 5.0 framework. The assertion function of Spring Cloud Gateway allows developers to define and match any information from HTTP Request, such as request header and parameters.
  • Filter a standard Spring WebFilter. There are two types of filters in Spring Cloud Gateway: Gateway Filter and Global Filter. The filter will modify the request and response

My understanding here is as follows:

  • The client sends a request to the Spring Cloud Gateway. If the gateway handler mapping determines that the request matches the route, it is sent to the gateway Web handler - the route.
  • Of course, how to determine the request and match is the concept of assertion. That is, the match is defined through the assertion function.
  • Based on the above figure, after the request url enters the routePredicate processor, it will arrive at the Filter processor to process the request and response.

That is, under the dispatcher handler manager, the assertion, routing forwarding and dynamic proxy of our gateway basically involve the above three cores

4. Conduct instance

4.1 basic experiment

Requirement: route the request containing / user to via the gateway system XAF gateway http://localhost:9000/user/1

Steps:

1. Create sub Maven project

The final directory is as follows:

2. We place it under the parent project, and then import additional dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    </dependencies>

We need to import the related packages of the gateway and open the registration discovery.

3. Write startup class

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

4. Configuration file

server:
  port: 10010
spring:
  application:
    name: api-gateway
eureka:
  client:
    service-url:
      defaultZone: HTTP://127.0.0.1:10086/eureka
  instance:
    prefer-ip-address: true

Here, we set the gateway port to 10010, and Eureka has set the corresponding web address.

The final display is as follows:

That is, ip is 127.0.0.1

The port is 10010

5. To modify the configuration file, we need to proxy the gateway to user

server:
  port: 10010
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: user-service-route
          #uri: HTTP://127.0.0.1:9000
          uri: lb://user-service
          predicates:
            - Path=/user/**
eureka:
  client:
    service-url:
      defaultZone: HTTP://127.0.0.1:10000/eureka
  instance:
    prefer-ip-address: true

Here, we proxy all requests that comply with the Path rule to the address specified by the uri parameter in this example. In addition, we will proxy the Path containing requests starting with / user / * * to http://127.0.0.1:10010

6. Start test

2021-11-02 09:19:50.272  INFO 7304 --- [ctor-http-nio-2] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client user-service initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=user-service,current list of Servers=[localhost:9001, localhost:9000],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone;	Instance count:2;	Active connections count: 0;	Circuit breaker tripped count: 0;	Active connections per server: 0.0;]}
Flipping property: user-service.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647

We can see that we have registered two user service ports of 9001 and 9000, and can use one of them for service with load balancing.

4.2 advanced experiment

Prefix addition and deletion of Routing: if the request address of the client is inconsistent with the service address of the micro service, you can add and remove the path prefix by configuring the path filter.

1. Add prefix: add a prefix path to the request address and then use it as the service address of the agent.

http://127.0.0.1:10010/1 --> http://127.0.0.1:9000/user/1 Add prefix path / user

2. Remove prefix: remove some prefix paths from the path in the request address, and then serve as the service address of the agent.

http://127.0.0.1:10010/api/user/1 --> http://127.0.0.1:9000/user/1 Remove prefix path / API

4.2.1 adding prefix

  cloud:
    gateway:
      routes:
        - id: user-service-route
          #uri: HTTP://127.0.0.1:9000
          uri: lb://user-service
          predicates:
            - Path=/**
          filters:
            # Add prefix to request path
            - PrefixPath=/user

After operation:

We can see that at this time, the filter of the core concept appears and modifies the requested url. That is, specify the prefix added by the route through PrefixPath=/xxx.

4.2.2 removing prefixes

cloud:
	gateway:
		routes:
			# The routing id can be written at will
			- id: user-service-route
			# Service address of agent
			uri: lb://user-service
			# Route assertion, you can configure the mapping path
			predicates:
				- Path=/api/user/**
			filters:
				# It means filtering 1 path, 2 means two paths, and so on
				- StripPrefix=1

summary

We have created a gateway service, which is used to dynamically route the user service. The full text shows the more basic part of the gateway. In actual production and life, we still need to make more configuration. Since novice Xiaobai has not found more information yet, please understand. Thank you for reading

Tags: Spring Cloud Microservices gateway

Posted on Tue, 02 Nov 2021 17:30:24 -0400 by dkruythoff