Application practice of Gateway

Keywords: Java Spring Cloud Microservices

Gateway overview

In essence, the gateway should provide an access to various services, and provide services to receive and forward all internal and external client calls, as well as authority authentication, flow restriction control and so on. Spring Cloud Gateway is a gateway component developed by spring company based on Spring 5.0, Spring Boot 2.0 and other technologies. It aims to provide a simple and effective unified API entry for microservice architecture, which is responsible for service request routing, composition and protocol conversion. It also provides functions such as permission authentication, monitoring and flow restriction based on Filter chain.

  • advantage:

1. Strong performance: 1.6 times that of Zuul, the first generation gateway

2. Powerful functions: many practical functions are built in, such as forwarding, monitoring, current limiting, etc

3. Elegant design and easy expansion

  • shortcoming

1. Rely on Netty and WebFlux, not the traditional server programming model

2. Spring Boot2.0 or above is required to support

Entry business implementation

Step 1: create the SCA gateway module (if it already exists, you don't need to create it). Its pom.xml file is as follows:

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

Step 2: create application.yml (if it already exists, there is no need to create it), and add relevant configurations. The code is as follows:

server:
  port: 9000
spring:
  application:
    name: sca-gateway
  cloud:
    gateway:
        routes: #Configure gateway routing rules
          - id: route01  #Routing id, you can specify a unique value by yourself
            uri: http://localhost:8081 / # the url forwarded by the gateway
            predicates: ###Assertion: match request rule
              - Path=/nacos/provider/echo/**  #Request path definition, which corresponds to resources in uri
            filters: ##Gateway filter is used to judge, analyze and process the content in the predicate
              - StripPrefix=1 #Remove the first layer path in the path before forwarding, such as nacos

Among them, route is one of the most basic components in gateway, which represents a specific routing information carrier. The following information is mainly defined:

id, Route identifier, which is different from other routes.
uri, the destination uri pointed by the route, that is, the micro service to which the client request is finally forwarded.
Predicate, the function of assertion (predicate) is to judge conditions. Routing will be executed only when all assertions return true.
filter, which is used to modify request and response information.
 

Step 3: create a startup class

Section interview analysis?

  • What is a gateway? Service access (flow) is an entrance, similar to the "Customs" in life“
  • Why use a gateway? (service security, unified service portal management, load balancing, current limiting, authentication)
  • Initial build process of Spring Cloud Gateway application (add dependency, configure)
  • Who is the bottom layer for Gateway service startup? (Netty network programming framework ServerSocket)
  • Must the Gateway service register in the registry when forwarding requests? (not necessarily, it can be accessed directly through the remote url)

Implementation of load balancing in Gateway?

Step 1: add service discovery dependency in the project. The code is as follows:

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

Step 2: modify its configuration file. The code is as follows:

server:
  port: 9000
spring:
  application:
    name: sca-gateway
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    gateway:
      discovery:
        locator:
          enabled: true  #Enable route creation through serviceId of service registry
      routes:
        - id: route01
          ##uri: http://localhost:8081/
          uri: lb://SCA provider # Lb is the service prefix (the abbreviation of load balancing words) and cannot be written arbitrarily
          predicates: ###Matching rules
              - Path=/nacos/provider/echo/**
          filters:
              - StripPrefix=1 #Remove the first layer path in the path before forwarding, such as nacos

Where lb refers to obtaining microservices from nacos by name and following the load balancing policy. At the same time, it is recommended to open the gateway log at the development stage. The code is as follows:

logging:
  level:
    org.springframework.cloud.gateway: debug

Predicate enhanced analysis (understanding)

Common predicate factories are as follows:

Assertion factory based on Datetime type

This type of assertion is judged according to time, mainly in three ways:

1) AfterRoutePredicateFactory: determines whether the request date is later than the specified date
2) BeforeRoutePredicateFactory: determines whether the request date is earlier than the specified date
3) BetweenRoutePredicateFactory: judge whether the request date is within the specified time period

-After=2020-12-31T23:59:59.789+08:00[Asia/Shanghai]

The request is forwarded only when the time at the time of the request is After the configured time. If the time at the time of the request is not After the configured time, 404 not found will be returned. The time value can be obtained through ZonedDateTime.now().

header based assertion factory HeaderRoutePredicateFactory

Judge whether the request Header has the given name and the value matches the regular expression. For example:

-Header=X-Request-Id, \d+

Assertion factory based on Method request Method

MethodRoutePredicateFactory receives a parameter to judge whether the request type matches the specified type. For example:

-Method=GET

Assertion factory based on Query request parameters, QueryRoutePredicateFactory:

Receive two parameters, request param and regular expression, and judge whether the request parameter has the given name and the value matches the regular expression. For example:

-Query=pageSize,\d+

Filter enhanced analysis (understand)

summary

Filter is to process requests and responses during request delivery. Gateway filters can be divided into two types: GatewayFilter and GlobalFilter. Among them:

  1. Gateway filter: applied to a single route or a packet route.
  2. GlobalFilter: applies to all routes.

Gateway current limiting design, current limiting quick start

Step 1: add dependency
On the basis of the original spring cloud starter gateway dependency, add the following two dependencies, for example:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>

Step 2: add sentinel and routing rules (if they already exist, there is no need to set them)

routes:
  - id: route01
    uri: lb://sca-provider
    predicates: ###Matching rules
      - Path=/provider/echo/**
sentinel:
  transport:
    dashboard: localhost:8180 #Sentinel console address
  eager: true  #Cancel the lazy loading of Sentinel console, that is, the project starts and connects

Step 3: start the gateway project and check the gateway menu of sentinel console.
When starting, add the jvm parameter of sentinel. Through this menu, the gateway service can display a different menu on the sentinel console. The code is as follows.

-Dcsp.sentinel.app.type=1
 

If it is in idea, you can refer to the following figure for configuration

  Return value of customized flow control gateway:

@Configuration
public class GatewayConfig {
    public GatewayConfig(){
        GatewayCallbackManager.setBlockHandler( new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Map<String,Object> map=new HashMap<>();
                map.put("state",429);
                map.put("message","two many request");
                String jsonStr=JSON.toJSONString(map);
                return ServerResponse.ok().body(Mono.just(jsonStr),String.class);
            }
        });
    }
}

Where Mono is a Publisher object that emits 0-1 elements

Analysis of key and difficult points:

  • Background of the birth of gateway? (first: unified entrance for microservice access, second: protection of system services, and third, unified authentication, authorization and current limitation)
  • Gateway selection? (Netifix Zuul,Spring Cloud Gateway,...)
  • Entry implementation of Spring Cloud Gateway (add dependency, routing configuration, startup class)
  • Load balancing in Spring Cloud Gateway? (gateway service registration, service discovery, accessing specific service instances based on uri:lb: / / service id)
  • Assertion configuration in Spring Cloud Gateway? (just master several commonly used ones, which can be checked through the search engine)
  • Filter configuration in Spring Cloud Gateway? (master the two types of filters - local and global)
  • Current limiting design in Spring Cloud Gateway? (Sentinel)

Posted by matscott on Tue, 30 Nov 2021 07:05:57 -0800