Spring Cloud Gateway: Gateway

gateway

The API gateway is to realize the unified entrance between the front-end project and the server-side project.
Nginx realizes the entrance called between the user and the front-end project.
The Ribbon implementation is a load balancing algorithm for mutual calls between the back-end services.
insert image description here

The role of the API gateway is to bring together the APIs provided by various services to the outside world, making it look like a unified interface to the outside world. Also provide additional functionality in the gateway.

Hello world

1. Build Eureka Server
2. Build application client cluster
3. Build Gateway gateway microservice
1. Import 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>

2. Write yml configuration file

server:
  port: 9999
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
spring:
  application:
    name: cloud-gateway
  cloud: # spring cloud相关配置的常用前缀
    gateway: # 网关技术配置前缀
      discovery: # 自动发现工具
        locator: # 本地逻辑
          enabled: true # 开启自动发现工具的本地路由逻辑
          lower-case-service-id: true # 把从EurekaServer上发现的服务名称,转换成全小写,只要小写的服务名称才能访问,大写的不行!!!!!!

4. Start the service
The local routing rules of the automatic discovery tool are:
request path - http://gateway IP: gateway port/service name of the microservice/the specific address to be accessed
gateway is automatically resolved, and the 'microservice' in the request address Service name' interception, check from the service list discovered by Eureka Client, if there is a service with the same name, start forwarding.
Such as: http://localhost (gateway IP):9999 (gateway port)/application (service cluster name)/save (specific access address)

Routing: Route

A route includes ID, URI, Predicate collection, and Filter collection.
In Route, ID is custom, but unique, and URI is an address.
Predicate: pre-routing condition and content.
Filter is responsible for doing something "before" or "after" the proxy service after routing.

Predicate: Predicate

Verify the request sent by the front end
1.Path: A predicate used to match routing address rules.

spring:
  cloud: 
    gateway:
      discovery:
        locator:
          enabled: false # 关闭自动发现工具的本地路由逻辑
          lower-case-service-id: true 
      routes: 
        - id: application-service # 路由的唯一名称,随便定义,不重复即可
          uri: lb://application-service # 规则满足后,转发到的地址。lb是spring cloud gateway支持的一种协议名
          predicates: Path=/edit # 谓词  路由地址规则  

Path=/edit/** 代表所有访问url中代用edit的都可以走这个路由

2.Query: Check whether the request url contains the specified request parameters and whether the parameter values ​​meet the requirements. Only the request address parameters can be verified, that is, the /path? parameter

方式一: 只能指定是否有指定请求参数,不能指定参数值
predicates: Path=/demo/**,Query=abc

方式二: 常用,可以指定请求参数及参数值,但是不能指定参数值中带有","的参数值
predicates: 
  - Path=/demo/**
  - Query=name,fs.* # 请求参数必须包含name,请求参数的值必须以 fs开头
  - Query=age,18 # 请求参数必须包含age

方式三:
predicates: 可以指定请求参数值中带有","的参数值
  - Path=/demo02
  - name: Query
    args:
      param: abc
      regexp: 12,3

3.Header: Verify whether the request contains the specified request header and whether the value of the request header meets the requirements.
4.Method: Request method. Multiple values ​​are supported, separated by commas
5.Cookie: Contains the specified cookie name and a value that meets specific regular requirements: If the cookie parameter value is a regular expression
**

  predicates:
    - Path=/service/**  
    - Header=Host,.* # 请求头必须有Host,值为任意字符串
    - Header=abc,123 # 请求头中包含abc,且值为123
	- Method=GET,POST # 请求方式必须是GET或POST
    - Cookie=name,bjsxt.* # 请求必须包含名称是name,值符合bjsxt开头的cookie。

6.RemoteAddr: The client IP that is allowed to access

  predicates:
    - Path=/service/** 
    - RemoteAddr=192.168.41.252 # 客户端IP必须是192.168.41.252

7.Host: Match the value of the Host request header in the request. Satisfying the Ant pattern (learned previously in Spring Security) can be used:

  • ? matches a character
  • * matches 0 or more characters
  • ** matches 0 or more directories
  predicates:
    - Path=/service/** 
    - Host=127.0.0.1:9999 # 请求头Host值必须是127.0.0.1:9999

8. Time limit:
Generally, only one of the following three can exist.
Before: Before the specified time point
After: After the specified time point.
Between: The request must be within the set time range before routing and forwarding.

  predicates:
    - Path=/service/** 
    - Before=2022-10-01T18:00:00.000+08:00[Asia/Shanghai] # 2022-10-01晚18点前可以访问
    - After=2020-10-01T08:00:00.000+08:00[Asia/Shanghai] # 2020-10-01早8点后可以访问
	- Between=2020-10-01T08:00:00.000+08:00[Asia/Shanghai],2022-10-01T18:00:00.000+08:00[Asia/Shanghai] # 2020-10-01早8点后,2022-10-01晚18点前可以访问

9. Weight: Specify group weight for service name
Weight=group name, load balancing weight
Example: Register two services in Eureka, the services (projects) are the same, and the application names are called application-service1 and application-service2 respectively .
When Gateway matches routes, application-service1 will account for 20%, and application-service2 will account for 80%.

- id: application-service1
  uri: lb://application-service1
  predicates:
    - Path=/service/**
    - Weight=group1,2
- id: application-service2
  uri: lb://application-service2
  predicates:
    - Path=/service/**
    - Weight=group1,8

Filter: Filter


After the route is forwarded, the route filter that runs before and after the execution of the proxied service : the built-in Filter implementations of the framework are all route filters, and they are all GatewayFilter implementation types.
Global filter: The framework does not have a built-in global filter implementation, which needs to be customized. The global filter needs to implement the interface GlobalFilter.

          filters: #/配置路由规则
            - stripPrefix=1 #跳过路径中的前几级发送给下游地址
            - AddRequestHeader=sxt,123 #给下游请求添加请求头
            - AddRequestParameter=abc,123 #给下游服务传递请求参数
            - AddResponseHeader=cou,javaEE #设置响应头
            - DedupeResponseHeader=cou,RETAIN_FIRST #当相应头重复后﹑保留第一个
            - SetPath=/{
    
    segment} #重新的设置路徭

Gateway implements current limiting: RequestRateLimiter filter

Common current-limiting algorithms
1. Counter algorithm: Each request adds one to the counter, and when the set value is reached, other requests are rejected. At the beginning of the next second, the count is cleared and restarted.
2. Leaky Bucket Algorithm: Regardless of the number of requests, requests are processed at a constant speed
3. Token Bucket Algorithm: Tokens are placed in the bucket, and the request can only continue to execute after obtaining the token. No matter how many requests are requested, the execution rate is determined by the production token Rate control.
Token bucket algorithm
1. Import 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>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. Create a new key parser
Note that IP parsing is used here

@Component
public class MyKeyResolver implements KeyResolver {
    
    
    @Override
    public Mono<String> resolve(ServerWebExchange exchange) {
    
    
        String ip = exchange.getRequest() // 获取请求对象
                .getRemoteAddress() // 获取客户端地址对象 InetSocketAddress
                .getAddress() // 获取客户端地址对象 InetAddress
                .getHostAddress(); // 获取客户端的主机地址(IP或唯一的主机名)
        return Mono.just(ip); // 创建返回结果对象
    }
}

3.yml configuration file

          filters:
            - name: RequestRateLimiter
              args:
                keyResolver: '#{@xxx}'
                redis-rate-limiter.replenishRate: 1 # 每秒令牌生成速率
                redis-rate-limiter.burstCapacity: 2 # 令牌桶容量上限

4. Test:
Use JMeter to access http://localhost:9999/save several times. The result is that 2 requests can be processed in the first second (token bucket upper limit), and 1 request can be processed in subsequent seconds (token generation rate ).

Use Gateway to achieve service degradation

1. Import dependencies

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

2. Create a backing method in the Gateway controller

@RestController
public class MyController {
    
    
    @RequestMapping("/fallback")
    public String show(){
    
    
        return "托底方法";
    }
}

3.yml configuration

          filters:
            - name: Hystrix
              args:
                name: fallback # 随意定义的名称。相当于@HystrixCommand注解中的commandKey属性。
                # 如果转发的服务不可用,请求转发到当前Gateway模块映射路径为fallback(随意命名和映射路径一致即可)的控制单元上。
                fallbackUri: forward:/fallback 

custom global filter

/**
 * 自定义全局过滤器。
 * 必须实现接口GlobalFilter
 * 当前类型的对象,必须被spring容器管理。
 * 无须配置,所有路由都生效。
 *
 * 执行顺序:
 *  先执行网关过滤器,后执行全局过滤器
 *  多个全局过滤器,执行顺序由Spring boot扫描管理当前对象的顺序决定。
 *  每个过滤器,都是完整执行后,才执行下一个过滤器。
 */
@Component
public class MyGlobalFilter implements GlobalFilter {
    
    
    /**
     * 过滤方法。
     * 实现上,只有唯一的要求。必须调用方法chain.filter(exchange),并把方法的返回值,返回。
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    
    
        System.out.println("前置全局过滤");
        //放行/执行下一个过滤器
        Mono<Void> result = chain.filter(exchange);
        System.out.println("后置全局过滤");
        return result;
    }
}

Execution process in GateWay

1. The gateway client accesses the Gateway gateway, and the Handler Mapping in the Gateway processes the request URL.
2. After the processing is completed, it will be processed by the Web Handler, which will be filtered by the Filter when the Web Handler is running. The first half of the code in Filter is the code to process the request.
3/ After the processing is completed, call the real proxied service; the proxied service returns the response result, and the result will be filtered and processed by the second half of the code in Filter; 4, after the operation is
completed, the result is returned to Web Handler, and then returned to Handler Mapping, finally response to the client.

The bottom layer of GateWay: The bottom layer framework is Netty (NIO): to encapsulate the content in java.net [NIO] AIO to encapsulate

Guess you like

Origin blog.csdn.net/m0_56182317/article/details/130217124