當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot2.1.9 分布式锁ShedLock不执行坑
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot2.1.9 分布式锁ShedLock不执行坑
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、起由
@Configuration @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT30S") public class TimerTaskConfig implements SchedulingConfigurer {@Beanpublic LockProvider scheduledLockConfiguration(RedisConnectionFactory redisConn) {return new RedisLockProvider(redisConn);}}SpringBoot Scheduled調度池的線程條數默認為1,多定時任務會積壓等待延遲執行。
一下是兩種修改方式
(1)@Async注解
@Async注解會異步執行調度任務,避免任務多積壓不執行。
也帶來了新的問題:任務執行超時沒有被分布式鎖鎖住。
由于任務異步執行,分布式鎖代碼執行立即返回了,耗費時間幾乎為0s,也就是ShedLock配置的lockAtLeastFor生效,lockAtMostFor是永遠不生效的。
(2)配置多線程調度池
配置多線程的調度池,可以避免多任務積壓,任務執行超時也可以控制。
?
二、配置多線程調度池
從博客網站里查來的調度池配置方式
@Configuration @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT30S") public class TimerTaskConfig implements SchedulingConfigurer {@Beanpublic LockProvider scheduledLockConfiguration(RedisConnectionFactory redisConn) {return new RedisLockProvider(redisConn);}@Overridepublic void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {scheduledTaskRegistrar.setScheduler(setTaskExecutors());}@Bean(destroyMethod="shutdown")public ScheduledExecutorService setTaskExecutors(){return Executors.newScheduledThreadPool(10); // 10個線程來處理。} }配置后定時任務可以執行,發布到多臺機器后,發現所有的機器都在執行相同的定時任務,ShedLock不起作用了。
分析原因:
給scheduledTaskRegistrar注冊了一個沒有lock的scheduler ScheduledExecutorService,而不是LockableTaskScheduler。
?
三、正確的配置
@Configuration @EnableScheduling @EnableSchedulerLock(defaultLockAtMostFor = "PT30S") public class TimerTaskConfig {@Beanpublic LockProvider scheduledLockConfiguration(RedisConnectionFactory redisConn) {return new RedisLockProvider(redisConn);}@Bean(destroyMethod="shutdown")public ScheduledExecutorService setTaskExecutors(){return Executors.newScheduledThreadPool(10); // 10個線程來處理。} }?
總結
以上是生活随笔為你收集整理的SpringBoot2.1.9 分布式锁ShedLock不执行坑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 现捞的配料和制作方法 现捞现卤配方与制作
- 下一篇: 潘神的迷宫影评 如何评价潘神的迷宫