gateway断言Predicate
Predicate和组合一批断言,gateway断言种类如下。定义个predicates下面可以挂多个断言类型。这些断言类型组合在一起影响断言结果。当满足断言那么就进入对应uri。在企业应用中,使用最多的就是Path。
断言种类
- After:匹配在这个时间之后
- Before:在这个时间之前
- Between:在这个时间区间内
- Cookie:接收Cookie中匹配的参数和值
- Header:接收Header中匹配的参数和值
- Host:匹配Host,接收是主机名列表
- Method:匹配http请求中的GET或者POST等
- Path:使用最多的,匹配路径
- Query
- RemoteAddr
- Weight
After
spring:
cloud:
gateway:
routes:
- id: user
uri: lb://user
predicates:
- Path=/cjxz/**
- After=2026-01-10T21:40:10.529+08:00[Asia/Shanghai]
filters:
- StripPrefix=1 # 去掉第一个路径:/cjxz/
当请求路径:localhost:9999/cjxz/hello 首先匹配断言中的Path发现满足,继续匹配After发现不满足(当前调用时间是:2025-01-09)不满足就报错
{
"timestamp": "2026-01-09T02:19:12.882+00:00",
"path": "/cjxz/hello",
"status": 404,
"error": "Not Found",
"message": null,
"requestId": "a8cec341-1"
}
Before
spring:
cloud:
gateway:
routes:
- id: user
uri: lb://user
predicates:
- Path=/cjxz/**
- Before=2026-01-10T21:40:10.529+08:00[Asia/Shanghai]
filters:
- StripPrefix=1 # 去掉第一个路径:/cjxz/
当请求路径:localhost:9999/cjxz/hello 首先匹配断言中的Path发现满足,继续匹配Before发现满足(当前调用时间是:2025-01-09),调用成功
hello xxx ...9002
Between
spring:
cloud:
gateway:
routes:
- id: user
uri: lb://user
predicates:
- Path=/cjxz/**
- Between=2026-01-08T21:40:10.529+08:00[Asia/Shanghai],2026-01-10T21:40:10.529+08:00[Asia/Shanghai]
filters:
- StripPrefix=1 # 去掉第一个路径:/cjxz/
当请求路径:localhost:9999/cjxz/hello 首先匹配断言中的Path发现满足,继续匹配Between发现满足(当前调用时间是:2025-01-09,在8-10号之间),调用成功
hello xxx ...9002
Header
需要再Header里面添加相应的参数,并且满足参数的要求。例如下面- Header=reqId,\d+表示需要再header里面添加reqId参数,并且这个参数需要满足全部是数字的正则表达式
spring:
cloud:
gateway:
routes:
- id: user
uri: lb://user
predicates:
- Path=/cjxz/**
- Between=2026-01-08T21:40:10.529+08:00[Asia/Shanghai],2026-01-10T21:40:10.529+08:00[Asia/Shanghai]
- Header=reqId,\d+
filters:
- StripPrefix=1 # 去掉第一个路径:/cjxz/
下面是请求的curl
curl --location --request GET 'localhost:9999/cjxz/hello' \
--header 'reqId: 8786768786767878'
可以看到当请求header里面添加reqId并且是全部数字才能请求到。然后同时满足上面的Path;Between两个条件
Method
在看一下Method这个断言。例如现在只要是POST;GET才能进来
spring:
cloud:
gateway:
routes:
- id: user
uri: lb://user
predicates:
- Path=/cjxz/**
- Between=2026-01-08T21:40:10.529+08:00[Asia/Shanghai],2026-01-10T21:40:10.529+08:00[Asia/Shanghai]
- Header=reqId,\d+
- Method=POST,GET
filters:
- StripPrefix=1 # 去掉第一个路径:/cjxz/
GET请求:
curl --location --request GET 'localhost:9999/cjxz/hello' \
--header 'reqId: 8786768786767878'
------响应结果
hello xxx ...9002
Path
用来匹配路径,路径只要是cjxz或者cjxz1都会走入user里面。这个在企业使用最多。一般只要是微服务,都会有不同的服务。例如basic;user;item等等。然后通过服务名称走入对应的应用。
spring:
cloud:
gateway:
routes:
- id: user
uri: lb://user
predicates:
- Path=/cjxz/**,/cjxz1/**
- Between=2026-01-08T21:40:10.529+08:00[Asia/Shanghai],2026-01-10T21:40:10.529+08:00[Asia/Shanghai]
- Header=reqId,\d+
- Method=POST,GET
filters:
- StripPrefix=1 # 去掉第一个路径:/cjxz/