断言可以匹配 HTTP 请求中的所有内容,如请求头、请求体、请求参数等,如果请求与断言匹配,则进行路由,否则不路由。
断言顶层接口是 java8 的 java.util.function.Predicate。
<br/>
其实在启动网关服务时,日志就会输出下面的断言,种类很多,下面列举几个常用的断言。
```
...: Loaded RoutePredicateFactory [After]
...: Loaded RoutePredicateFactory [Before]
...: Loaded RoutePredicateFactory [Between]
...: Loaded RoutePredicateFactory [Cookie]
...: Loaded RoutePredicateFactory [Header]
...: Loaded RoutePredicateFactory [Host]
...: Loaded RoutePredicateFactory [Method]
...: Loaded RoutePredicateFactory [Path]
...: Loaded RoutePredicateFactory [Query]
...: Loaded RoutePredicateFactory [ReadBody]
...: Loaded RoutePredicateFactory [RemoteAddr]
...: Loaded RoutePredicateFactory [XForwardedRemoteAddr]
...: Loaded RoutePredicateFactory [Weight]
...: Loaded RoutePredicateFactory [CloudFoundryRouteService]
```
[TOC]
# 1. After
```yml
spring:
cloud:
gateway:
routes:
- id: assemb-server-payment
uri: lb://assemb-server-payment
predicates:
- Path=/order/**
#当过了 After 指定的时间后才能路由到 /order/**
- After=2021-11-18T16:39:38.482+08:00[Asia/Shanghai]
```
上面一大串的字符串可以如下获取:
```java
public static final String getZoneDateTime() {
//默认时区
ZonedDateTime zbj = ZonedDateTime.now();
return zbj.toString();
}
```
<br/>
# 2. Between
```yml
spring:
cloud:
gateway:
routes:
- id: assemb-server-payment
uri: lb://assemb-server-payment
predicates:
- Path=/order/**
#当时间在两者之间时才能路由到 /order/**
- Between=2021-11-18T16:42:23.093+08:00[Asia/Shanghai],2021-11-18T20:42:23.093+08:00[Asia/Shanghai]
```
<br/>
# 3. Cookie
```yml
spring:
cloud:
gateway:
routes:
- id: assemb-server-payment
uri: lb://assemb-server-payment
predicates:
- Path=/order/**
#当携带Cookie时才能路由到 /order/**
- Cookie=chocolate, ch.p
```
<br/>
# 4. Header
```yml
spring:
cloud:
gateway:
routes:
- id: assemb-server-payment
uri: lb://assemb-server-payment
predicates:
- Path=/order/**
#当携带指定的请求头时才能路由到 /order/**
- Header=X-Request-Id, \d+
```
<br/>
# 5. Host
```yml
spring:
cloud:
gateway:
routes:
- id: assemb-server-payment
uri: lb://assemb-server-payment
predicates:
- Path=/order/**
#只要携带下面两个主机之一便可以路由到 /order/**
- Host=**.somehost.org,**.otherhost.org
```
<br/>
# 6. Query
```yml
spring:
cloud:
gateway:
routes:
- id: assemb-server-payment
uri: lb://assemb-server-payment
predicates:
- Path=/order/**
#需要携带参数username才能路由到 /order/**
- Query=username
```
<br/>
# 7. Method
```yml
spring:
cloud:
gateway:
routes:
- id: assemb-server-payment
uri: lb://assemb-server-payment
predicates:
- Path=/order/**
#只有GET请求才能路由到 /order/**
- Method=GET
```