参考:官方文档
https://www.cnblogs.com/babycomeon/p/11161073.html
Spring Cloud
版本:Hoxton.SR5
Spring Cloud Gateway
版本:2.2.3.RELEASE
1 简介
Spring Cloud Gateway
内置了很多Predicate
,用来制定路由匹配规则。
Predicate
来源于Java 8
,是Java 8
中引入的一个函数,Predicate
接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将Predicate
组合成其他复杂的逻辑(比如:与、或、非)。可以用于接口请求参数校验、判断新老数据是否有变化需要进行更新操作。
在Spring Cloud Gateway
中Spring
利用Predicate
的特性实现了各种路由匹配规则,有通过Header
、请求参数等不同的条件来进行作为条件匹配到对应的路由。
下图总结了内置的Predicate
:
2 内置Predicate
2.1 匹配请求时间
2.1.1 AfterRoutePredicateFactory
AfterRoutePredicateFactory
可以配置一个时间datetime
,类型是ZonedDateTime
。这个Predicate
会匹配那些在设定的时间之后到达的请求。
ZonedDateTime
是Java 8
中日期时间功能类,用于表示带时区的日期与时间信息的类,ZonedDateTime
支持通过时区来设置时间,中国的时区是:Asia/Shanghai
。
下面是在application.yml
文件中配置该Predicate
的例子:
spring:
cloud:
gateway:
routes:
- id: after_route
uri: https://example.org
predicates:
- After=2020-06-26T00:00:00+08:00[Asia/Shanghai]
2.1.2 BeforeRoutePredicateFactory
BeforeRoutePredicateFactory
配置一个datetime
时间。这个Predicate
会匹配那些在设定时间之前到达的请求。
spring:
cloud:
gateway:
routes:
- id