一、@RefreshScope导致定时任务失效
当定时任务使用@RefreshScope想达到配置动态刷新时,你会发现定定时任务失效了,失效的原因和@RefreshScope的原理有关:配置的刷新会导致原来的对象被清除,需要重新使用对象才能出发生成新对象,但因为对象没了,又没法重新使用对象(死循环),所以导致了定时任务的失效。(这样描述是否恰当)
二、定时任务的动态刷新实现方式
1. @RefreshScope+RefreshScopeRefreshedEvent
RefreshScopeRefreshedEvent刷新作用域刷新事件
1.1 简单写法
@RefreshScope
@Component
public class TestTask implements ApplicationListener<RefreshScopeRefreshedEvent> {
@Value("${test.num}")
private String num;
@Scheduled(cron = "* * * * * *")
// @Scheduled(cron = "${test.cron}")// 可实现定时任务执行时间的动态刷新
public void schedule() {
System.out.println("============ 定时任务执行了,num["+num+"] ============");
}
@Override
public void onApplicationEvent(RefreshScopeRefreshedEvent event) {
}
}
1.2复杂写法
public interface RefreshScheduler {
default void materializeAfterRefresh() {
}
}
@Component
public class RefreshScopeListener implements ApplicationListener<RefreshScopeRefreshedEvent> {
private

本文详细探讨了在Spring Cloud中使用@RefreshScope导致定时任务失效的问题,并提供了多种动态刷新定时任务的实现方式,包括监听RefreshScopeRefreshedEvent事件、使用Environment、@ConfigurationProperties以及EnvironmentChangeEvent。同时,展示了如何通过正确处理对象生命周期来确保定时任务在配置刷新后仍能正常执行。
最低0.47元/天 解锁文章
1037

被折叠的 条评论
为什么被折叠?



