自定义 路由谓词工厂
我的代码
@Component
public class TimeBetweenRoutePredicateFactory
extends AbstractRoutePredicateFactory<TimeBetweenConfig> {
public TimeBetweenRoutePredicateFactory() {
super(TimeBetweenConfig.class);
}
@Override
public Predicate<ServerWebExchange> apply(TimeBetweenConfig config) {
LocalTime start = config.getStart();
LocalTime end = config.getEnd();
return exchange -> {
LocalTime now = LocalTime.now();
return now.isAfter(start) && now.isBefore(end);
};
}
/**
* 配置类 与 配置文件 映射关系
* @return
*/
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList("start","end");
}
public static void main(String[] args) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
System.out.println(dateTimeFormatter.format(LocalTime.now()));
}
}
main函数 打印的时间格式是:“6:36 PM”
所以我的配置如下:
gateway:
discovery:
locator:
#让 gateway 通过服务发现组件,找到其他微服务
enabled: true
routes:
- id: time_between
uri: lb://user-center
predicates:
- TimeBetween=9:24 AM, 6:24 PM
应用启动报错:
2020-10-23 18:40:15.257 ERROR 9429 --- [ask-Scheduler-1] o.s.s.s.TaskUtils$LoggingErrorHandler : Unexpected error occurred in scheduled task
reactor.core.Exceptions$ErrorCallbackNotImplemented: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'end' to java.time.LocalTime
Caused by: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'end' to java.time.LocalTime
Caused by: org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.time.LocalTime] for value '6:24 PM'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [6:24 PM]
Caused by: java.lang.IllegalArgumentException: Parse attempt failed for value [6:24 PM]
Caused by: java.time.format.DateTimeParseException: Text '6:24 PM' could not be parsed at index 0
Failed to bind properties under 'end' to java.time.LocalTime:
Property: end
Value: 6:24 PM
Origin: "end" from property source "source"
Reason: failed to convert java.lang.String to java.time.LocalTime
Action:
Update your application's configuration
面向未来微服务:熟练掌握Spring Cloud Alibaba
了解课程