在简介中简单介绍了Spring Cloud Gateway的配置方式和开发方式,本节将详细介绍其内置断言相关内容。

配置模式

  1. 简化配置模式
    简化配置是将路由的断言配置进行了简化,路由以id进行分组,每组配置中的匹配规则以列表方式配置,每条规则以“=”分隔,左侧是路由断言名称,右侧是此断言的参数,如下官方示例(通过Cookie值匹配转发路由):
spring:
  cloud:
    gateway:
      routes:
      - id: after_route #路由分组ID
        uri: https://example.org  #转发服务URI
        predicates:
        - Cookie=mycookie,mycookievalue #断言配置,此处“=”左侧 Cookie 指定使用 Cookie Route Predicate Factory,右侧 mycookie,mycookievalue 指定 Cookie 名称及值
  1. 完全配置模式
    完全配置模式则是相对于简化配置模式而言,断言相关配置更加完整,如下官方示例:
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie  #指定使用 Cookie Route Predicate Factory
          args:
            name: mycookie  #指定 Cookie 名称为 mycookie
            regexp: mycookievalue  #指定 mycookie 的值为 mycookievalue

路由匹配规则

Spring Cloud Gateway 自带了11种路由匹配规则(3.1.0版本),分别如下:

序号

规则

作用

断言名称

参数名

参数值

示例(predicates配置)

1

The After Route Predicate Factory

在指定时间之后的请求生效

After

datetime

包含时区的时间戳

After=2022-01-20T17:42:47.789-07:00[Asia/Shanghai]

2

The Before Route Predicate Factory

在指定时间之前的请求生效

Before

datetime

包含时区的时间戳

After=2022-01-20T17:42:47.789-07:00[Asia/Shanghai]

3

The Between Route Predicate Factory

在指定时间范围内的请求生效

Between

datetime

包含时区的时间戳

Between=2022-01-20T17:42:47.789-07:00[Asia/Shanghai],2023-01-20T17:42:47.789-07:00[Asia/Shanghai]

4

The Cookie Route Predicate Factory

根据指定的Cookie及其值进行匹配

Cookie

name,regexp

Cookie名及相应值

Cookie=chocolate, ch.p

5

The Header Route Predicate Factory

根据指定的请求头及其值进行匹配

Header

header,regexp

请求头及相应值

Header=X-Request-Id, \d+

6

The Host Route Predicate Factory

根据域名进行匹配

Host

patterns

需要匹配的域名,多个用逗号分隔,支持Ant风格的模式匹配

Host=**.somehost.org,**.anotherhost.org

7

The Method Route Predicate Factory

根据请求方式匹配

Method

methods

需要匹配的请求方式,多个用逗号分隔

Method=GET,POST

8

The Path Route Predicate Factory

根据请求路径匹配

Path

patterns, matchTrailingSlash

需要匹配的路径,支持Spring风格的模式匹配;默认matchTrailingSlash为true(后缀路径模式匹配)

Path=/red/{segment},/blue/{segment}

9

The Query Route Predicate Factory

根据请求参数匹配

Query

param,regexp

Query parameter名及其值(Java正则表达式,可不配置)

Query=green #Query parameter中包含green则匹配Query=red, gree. #Query parameter中包含red,其值匹配"gree."则匹配

10

The RemoteAddr Route Predicate Factory

根据请求方地址匹配

RemoteAddr

sources

请求方IP列表

RemoteAddr=192.168.1.1/24

11

The Weight Route Predicate Factory

根据权重进行路由

Weight

group,weight

分组及权重

Weight=group1, 8