写在前面 本文参考以下文章,请参考原文
springcloud(十五):服务网关 Spring Cloud GateWay 入门
Predicate & Spring Cloud Gateway 路由匹配规则
Predicate 来源于 Java 8,是 Java 8 中引入的一个函数,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。可以用于接口请求参数校验、判断新老数据是否有变化需要进行更新操作。
在 Spring Cloud Gateway 中 Spring 利用 Predicate 的特性实现了各种路由匹配规则,有通过 Header、请求参数等不同的条件来进行作为条件匹配到对应的路由。
在Spring Cloud Gateway--网关路由 简单示例了Spring Cloud Gateway的路由功能,现在讲一下Spring Cloud Gateway的路由规则。
1.通过时间匹配(datetime)
通过配置predicated 的 Before ,After ,Between 等属性,可以实现限制路由转发的时间段。时间对比:Spring 是通过 ZonedDateTime 来对时间进行的对比,ZonedDateTime 是 Java 8 中日期时间功能里,用于表示带时区的日期与时间信息的类,ZonedDateTime 支持通过时区来设置时间,中国的时区是:Asia/Shanghai
- Before Route Predicate 刚好相反,在某个时间之前的请求的请求都进行转发
- After Route Predicate 是指在这个时间之后的请求都转发到目标地址
- Between Route Predicate 只有在这段时间内的请求才进行转发
在Spring Cloud Gateway--网关路由 的例子基础上修改application.yml如下,就表示在这个时间之前可以进行路由,在这时间之后停止路由,修改完之后重启项重新启动网关服务,访问http://localhost:8080/discoveryClient,页面会报 404 没有找到地址
server:
port: 8080
spring:
cloud:
gateway:
routes:
- id: neo_route
uri: http://localhost:2001/
predicates:
- Path=/discoveryClient
- Before=2020-12-01T06:06:06+08:00[Asia/Shanghai]
修改application.yml如下,就表示在这个时间之后的时间可以进行路由,修改完之后重启项重新启动网关服务,访问http://localhost:8080/discoveryClient,会自动路由到 http://localhost:2001/discoveryClient