需求
我们看了官方提供的几个例子,如果都不满足呢?
举个例子: 实现一个类似 12306订票管控的需求: 早上6点到23点,才允许业务进行。
三部曲
第一步 搞配置类
package com.artisan.custom; import lombok.Data; import java.time.LocalTime; /** * @author 小工匠 * @version 1.0 * @description: TODO * @date 2022/2/14 0:21 * @mark: show me the code , change the world */ @Data public class CustomTimeBetweenConfig { private LocalTime startTime; private LocalTime endTime; }
第二步 搞自定义谓词工厂
类名必须要以RoutePredicateFactory结尾,然后继承AbstractRoutePredicateFactory
package com.artisan.custom; import lombok.extern.slf4j.Slf4j; import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; import java.time.LocalTime; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; /** * @author 小工匠 * @version 1.0 * @description: TODO * @date 2022/2/14 0:20 * @mark: show me the code , change the world */ @Component @Slf4j public class CustomTimeBetweenRoutePredicateFactory extends AbstractRoutePredicateFactory<CustomTimeBetweenConfig> { public CustomTimeBetweenRoutePredicateFactory() { super(CustomTimeBetweenConfig.class); } /*** * 真正的业务判断逻辑 * @param config * @return */ @Override public Predicate<ServerWebExchange> apply(CustomTimeBetweenConfig config) { LocalTime startTime = config.getStartTime(); LocalTime endTime = config.getEndTime(); return new Predicate<ServerWebExchange>() { @Override public boolean test(ServerWebExchange serverWebExchange) { LocalTime now = LocalTime.now(); //判断当前时间是否在在配置的时间范围类 return now.isAfter(startTime) && now.isBefore(endTime); } }; } /** * 用于接受yml中的配置CustomTimeBetween=上午6:00,下午11:00 * * @return */ @Override public List<String> shortcutFieldOrder() { return Arrays.asList("startTime", "endTime"); } }
第三部 搞配置
在yml配置中谓词配置是以我们自定义类CustomTimeBetweenRoutePredicateFactory
去除了RoutePredicateFactory接受开头CustomTimeBetween
application-custom.yml
# 自定义谓词工厂 spring: cloud: gateway: routes: - id: custom-timeBetween #id必须要唯一 uri: lb://artisan-cloud-gateway-order predicates: #当前请求的时间必须在早上6点到 晚上11点 http://localhost:8888/selectOrderInfoById/1 #才会被转发 #到http://artisan-cloud-gateway-order/selectOrderInfoById/1 - CustomTimeBetween=上午06:00,下午11:00
激活profile
验证
public static void main(String[] args) { System.out.println(LocalTime.now()); }
现在是
访问肯定不行
debug走下
改改时间 符合规则 试试能行吗
OK, 妥妥的实现了
源码
https://github.com/yangshangwei/SpringCloudAlibabMaster