Gateway Before 路由断言工厂

Before 路由断言工厂只有一个参数,即日期时间(java ZonedDateTime)。该断言会匹配在指定日期时间之前发生的请求。例如:

spring:
 cloud:
   gateway:
     routes:
     - id: before_route
       uri: https://example.org
       predicates:
       - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

上面配置,before_route 路由将匹配山地(Mountain)时间(Denver 丹佛) 2017 年 1 月 20 日 17:42 之前提出的任何请求相匹配。

示例

将“Gateway 搭建网关服务”项目的配置文件 bootstrap.yml 内容使用如下配置替换:

server:
  # 网关端口
  port: 9000

spring:
  application:
    # 服务名称
    name: gateway-demo01
  cloud:
    # nacos
    nacos:
      discovery:
        server-addr: localhost:8848
        username: nacos
        password: nacos
        group: DEFAULT_GROUP

    # 网关路由配置
    gateway:
      # 网关路由配置
      routes:
        # 路由id,自定义,只要唯一集合
        - id: service-order
          # 路由的目标地址,lb 就是负载均衡,后面跟服务名
          # 需要集成 nacos 等服务注册中心
          uri: lb://service-order
          # 路由断言,也就是判断请求是否符合路由规则的条件
          predicates:
            # Before 断言:将匹配上海(东八区)2023-12-09 22:00:00.000 之前的请求
            - Before=2023-12-09T22:00:00.000-08:00[Asia/Shanghai]

重启网关服务,如下图:

Gateway Before 路由断言工厂

此时,使用 postman 调用订单接口,如下图:

Gateway Before 路由断言工厂

从上图可知,成功调用了订单接口。如果将时间改为 21 点,如下:

- Before=2023-12-09T21:00:00.000-08:00[Asia/Shanghai]

重启网关服务,访问如下图:

Gateway Before 路由断言工厂

服务访问失败,返回了 404 状态。

源码分析

下面是 Before 路由断言工厂的源码:

package org.springframework.cloud.gateway.handler.predicate;

//...

public class BeforeRoutePredicateFactory extends AbstractRoutePredicateFactory<BeforeRoutePredicateFactory.Config> {

    public static final String DATETIME_KEY = "datetime";

    public BeforeRoutePredicateFactory() {
       super(Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
       return Collections.singletonList(DATETIME_KEY);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
       // 配置信息
       ZonedDateTime datetime = config.getDatetime();
       return exchange -> {
          // 当前时间
          final ZonedDateTime now = ZonedDateTime.now();
          // 将当前时间和配置的时间进行比较
          return now.isBefore(datetime);
       };
    }

    public static class Config {
       private ZonedDateTime datetime;
       //...配置信息
    }
}
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号