02-Detailed explanation of the implementation of request routing and common assertion factories

Request routing

路由转发

Step 1: Create a new SpringBoot project such as gateway module, introduce gateway dependency and nacos service discovery dependency

<!--网关依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos服务发现依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

Step 2: Write the startup class ingateway模块

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

Step 3: Write basic configuration and routing rules

  • 路由名称(id): The unique representation of the route, user-defined only needs to be unique
  • 路由目标地址(uri): You can route to a fixed address, or you can route to a service and then select a service instance according to the load balancing rules.
  • 路由断言(predicates): Determine whether the request meets the conditions of routing rules (multiple rules can be set). If it meets the requirements, it will be forwarded to the matching host or interface.
  • 路由过滤器(filters): Perform some processing operations on the request or response
server:
  port: 10010 # 网关端口
spring:
  application:
    name: gateway # 服务名称
  cloud:
    nacos:
      server-addr: localhost:8848 # 将网关服务注册到nacos
      #server-addr: localhost:80 # 使用nginx反向代理功能
    gateway:
      routes: # 网关路由配置
        - id: userservice 
          uri: lb://userservice # 配置userservice服务的路由规则
          # uri: http://localhost:8081 
          predicates: 
            - Path=/user/** # 按照路径匹配,只要是以/user开头的请求路径就符合规则
        - id: orderservice 
          uri: lb://orderservice # 配置orderservice服务的路由规则
          predicates: 
            - Path=/order/** # 按照路径匹配,只要是以/order开头的请求路径就符合规则

Step 4: Start the gateway service. The gateway will forward the request to the corresponding service instance according to the specified routing rules. At this time,将网关端口号后面的地址拼接到要转发地址的端口号后面

  • When accesseshttp://localhost:10010/user/1, the gateway will forward the request tohttp://userservice/user/1
  • When accesseshttp://localhost:10010/order/101, the gateway will forward the request tohttp://orderservice/order/101
{
    "id": 1,
    "username": "柳岩",
    "address": "湖南省衡阳市"
}
{
    
    
    "id": 101,
    "price": 699900,
    "name": "Apple 苹果 iPhone 12 ",
    "num": 1,
    "userId": 1,
    "user": {
    
    
        "id": 1,
        "username": "柳岩",
        "address": "湖南省衡阳市"
    }
} 

The basic process of gateway implementation of routing

Insert image description here

assertion factory

常见的断言规则

The assertion rules we wrote in the configuration file are just strings. These assertion rules will be read byPredicate Factory(断言工厂) and converted into routing judgment conditions

SpringCloudGatewway provides 11 basicassertion factories, which are used to read user-defined assertion conditions and make judgments on requests a>

Insert image description here

Path表示按照路径匹配, this rule is processed byorg.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory

  • supports the use of ** to match any multi-layer path, {xx} to indicate that the placeholder can match one layer of paths
  • Supports setting multiple path rules, separated by commas
predicates:
# 最终将请求地址拼接到转发地址的端口号后面
- Path=/red/{
    
    segment},/blue/**

# 同时segment这个参数也可以通过网关过滤工厂拿到
Map<String, String> uriVariables = ServerWebExchangeUtils.getUriTemplateVariables(exchange);
String segment = uriVariables.get("segment");

AfterIt means that it can be forwarded to the routing target address after xx time, which can be used to upload websites for activities.

predicates:
- After=2031-04-13T15:14:47.433+08:00[Asia/Shanghai]

BeforeIndicates that it can be forwarded to the routing target address before xx time.

predicates:
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]

BetweenIndicates that it can be forwarded to the routing target address between two times.

predicates:
- Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

CookieIndicates that the request must be configured with the corresponding key and value in the cookie before it can be forwarded to the routing target address.

predicates:
- Cookie=chocolate, ch.p

Header means that the request must be configured with the request header X-Request-Id, \d+ means that the value is a numeric type, and it can be forwarded to the routing target address if the above conditions are met

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

HostIndicates that the requested host must match the specified expression in order to be forwarded to the routing target address

predicates:
- Host=**.somehost.org,**.anotherhost.org

MethodIndicates that the request method of the request is GET or POST before it can be forwarded to the routing target address.

predicates:
- Method=GET,POST

Query means that the request must contain the specified request parameter name and value. Multiple values ​​can be set and separated by commas. Support. to match any letters

predicates:
# key为Query,value为red或gree.或greet或greed等
- Query=red, gree.

RemoteAddrIndicates that the requested IP address must be within the specified range. The parameter is an array and multiple configurations can be configured. The parameter format is:IP/子网掩码

predicates:
- RemoteAddr=192.168.1.1/24

WeightIndicates that multiple routing target addresses are grouped into one group, and then different weights are set for different addresses.

spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8 # 80%的请求会路由给https://weighthigh.org
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2 # 20%的请求会路由给https://weightlow.org

Guess you like

Origin blog.csdn.net/qq_57005976/article/details/134968825