XV SpringCloudAlibaba minimalist introduction - Gateway integration Nacos

Posted by salhzmzm on Wed, 09 Feb 2022 13:33:32 +0100

preface

This article is a supplement. The previous Spring Cloud Gateway was integrated with Eureka as the registry. See< Service Gateway >Now let's talk about the integration of Spring Cloud Gateway and Nacos. This article only introduces the integration of Gateway and Nacos. Please combine< Service Gateway >You will gain more by watching together

1. Understanding of spring cloud gateway

Zuul It is an open source project of Netflix. Spring Cloud integrates it into its own sub component. zuul uses the multithread blocking model, which is essentially a synchronous Servlet. This model is relatively simple. The problem is that context switching between multithreads has overhead. The more threads, the greater the overhead. The fixed number of thread pools means that the number of requests that can be accepted is fixed. When the background requests become slow, in the face of a large number of requests, the threads in the thread pool are easy to be exhausted, and subsequent requests will be rejected.

In Zuul 2.0, it adopts Netty to realize asynchronous non blocking programming model. Asynchronous non blocking mode consumes less threads, consumes less thread on-line text switching, and can accept more requests. Its problem is that the thread model is relatively complex, which requires a deep study of the underlying principles and requires some effort.

Spring Cloud Gateway is the product of Spring Cloud. It is developed based on Spring 5 and Spring Boot 2.0. Spring Cloud Gateway appears to replace zuul. zuul 2.0 is not integrated in the higher version of Spring Cloud. Spring Cloud Gateway uses the high-performance Reactor mode communication framework Netty.

The goal of Spring Cloud Gateway is not only to provide a unified routing method, but also to provide the basic functions of the gateway based on the Filter chain, such as security, monitoring / indicators, and current limiting.

So in fact, the difference between Gateway and zuul 2.0 is not very big. They both use Netty high-performance communication framework, and their performance is very good.

1.2. Features of spring cloud gateway

The following features of Spring Cloud gateway are officially defined in Spring Cloud:

  • Based on Spring 5, project reactor and spring boot 2.0

  • Default integrated Hystrix circuit breaker

  • Default integration Spring Cloud DiscoveryClient

  • Predictions and Filters act on specific routes. They are easy to write

  • Support dynamic routing, current limiting and path rewriting

1.3. Core concepts of spring cloud gateway

Spring cloud gateway has several core components:

  • Filter:

The Spring Cloud Gateway Filter is similar to Zuul's Filter. It can process some business before and after the request is sent. Here, there are two types of filters: Gateway Filter, Gateway Filter and Global Filter. The differences between them will be discussed later.

  • Route:

The basic composition module of Gateway configuration is similar to Zuul's routing configuration module. A Route module 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 and the destination URI is accessed. To put it bluntly, it is to Route the url request to the corresponding resource (service), or a request. How should the Gateway forward the request to the downstream micro service and to whom.

  • Predicate:

For example, it can match the content from any Java request with the header 8 parameter. The input type of the assertion is a ServerWebExchange. The simple understanding is the matching rules for processing HTTP requests. Under what circumstances can the resource be hit to continue to access.

1.3. How spring cloud gateway works:

The working principle of Spring Cloud Gateway is similar to that of Zuul. The biggest difference is that there are only pre and post filters in the Gateway. The following is the official implementation flow chart:

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 handler runs the request through a chain of request specific filters. The reason why filters are separated by dashed lines is that filters can run logic before and after sending proxy requests. All "pre filter" logic is executed. Then issue a proxy request. After a proxy request is made, the after filter logic is run.

2. Getting started with spring cloud gateway

2.1. Create project import dependency

Project Name: springcloud-gateway-server-1110, import gateway infrastructure dependency

<!--1.Administration SpringBoot Dependence of-->
<parent>
    <groupId> org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.13.RELEASE</version>
</parent>
<!-- springcloud and alibaba Dependency declaration -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>

        <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>
<dependencies>
	<!--gateway-->
  <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
	<!--Service registration and discovery dependency-->

    <dependency>
        <groupId>com.alibaba.cloud </groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
</dependencies>

[note] there is no need to import the spring boot start web package here, which is already in the gateway dependency

2.2. Main configuration class

Enable service discovery through @ EnableDiscoveryClient annotation

//Service registration and discovery
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayServerApplication1110 {
    public static void main(String[] args) {
        SpringApplication.run(GatewayServerApplication1110 .class);
    }
}

2.3.yml configuration

The main configurations here are: service information, registry address, routing configuration, and cross domain content:

server:
  port: 1000
spring:
  application:
    name: service-gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848	#Nacos registry address
    gateway:
      discovery:
        locator:
          enabled: false #Open service name access method
          lower-case-service-id: true #Service name lowercase
      routes:
        - id : service-user #Specify the service name
          uri: lb://Service user # goes to the registry to find the service name
          predicates:    #Assertion, matching the path of access
            - Path=/user/**	#Service access path
          filters:
            - StripPrefix=1	#The / user access path will be removed when the request is forwarded
        - id: service-course #Specify the service name
          uri: lb://Service course # go to the registry to find the service name
          predicates:    #Assertion, matching the path of access
            - Path=/course/**    #Service access path
          filters:
            - StripPrefix=1    #The / user access path will be removed when the request is forwarded
      globalcors: #Cross domain configuration
        cors-configurations:
          '[/**]':
            allowedOrigins:
              - "http://127.0.0.1:8081 "# allow cross domain
              - "http://127.0.0.1:8082"
            allow-credentials: true
            allowed-headers: "*"
            allowedMethods:
              - GET
              - POST
              - DELETE
              - PUT
              - PATCH
              - OPTIONS
              - HEAD
              - CONNECT
              - TRACE


In addition to registering with Eureak, you also need to configure the route of gateway

  • spring. cloud. nacos. discovery. Server addr: is the address of Nacos registry, see:< Nacos service registration and discovery>
  • spring.cloud.gateway.discovery.locator.enabled=false: do not open the service name access method
  • spring. cloud. gateway. discovery. locator. Lower case service ID: true ignores the case of the service name. Both uppercase and lowercase can match
  • spring.cloud.gateway.routes.id: Specifies the service name of the route, which can be defined by yourself
  • spring. cloud. gateway. routes. Uri = LB: / / user server: go to the registry to find a service and request it in the way of load balancing. In fact, it is to find the service to be called.
  • spring. cloud. gateway. routes. Predictions: asserts that the path used here = / user / * *, that is, the path matching the access. If / user / is matched, the request can be routed (distributed) to the user server service.
  • spring.cloud.gateway.routes.filters: StripPrefix=1 is mainly used to process the prefix / user. The prefix will be removed when accessing the target service. This needs to be defined according to the url.

2.5. Access test

Start the registry, start the user service, and start the gateway access: http://localhost:1110/user/user/1 , the request will be made to the user service and the user data will be returned.

The article introduces that if you like it, give it a high praise

Topics: Spring Cloud gateway