配置中心实现定时任务动态更新

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

一、@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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值