ShedLock(https://github.com/lukas-krecan/ShedLock) 是一个轻量级的分布式定时任务锁组件,使用其可以满足我们上面的技术需求,ShedLock 官方简单自我介绍:
“ShedLock makes sure that your scheduled tasks are executed at most once at the same time. If a task is being executed on one node, it acquires a lock which prevents execution of the same task from another node (or thread). Please note, that if one task is already being executed on one node, execution on other nodes does not wait, it is simply skipped.
“
Shedlock 从严格意义上来说不是一个分布式任务调度框架,而是一个分布式锁。所谓的分布式锁,解决的核心问题就是各个节点中无法通信的痛点。各个节点并不知道这个定时任务有没有被其他节点的定时器执行,所以理论上只需要有一个各个节点都能够访问到的资源,用这个资源去标记这个定时任务有没有执行就可以了。
Shedlock 实现分布式锁,可以依赖如下组件:
- JdbcTemplate
- Mongo
- DynamoDB
- DynamoDB 2
- ZooKeeper (using Curator)
- Redis (using Spring
- RedisConnectionFactory)
- Redis (using Jedis)
- Hazelcast
- Couchbase
- ElasticSearch
- CosmosDB
- Cassandra
- Multi-tenancy
本文主要以来 Redis 为公共存储,实现定时任务的分布式锁。首先,我们假设你的 Spring Boot 项目已经引入了 Redis,在项目的 pom 文件中加入依赖:
开启定时任务锁:
“defaultLockAtMostFor = “PT30S” 表示默认锁的最大占用时间是 30s;
“
其次,在定时任务方法上,加上注解 @SchedulerLock:
启动多个节点,会发现,每次定时任务只有一个节点执行,定时任务执行后,在 Redis 里会看到两个 key:job-lock:default:testTask-1 和 job-lock:default:testTask-2。
Shedlock 通过 AOP,拿到 TaskScheduler 的行为做代理,并加入分布式锁实现所需要的功能。
上锁入口在 RedisLockProvider.java:
可以看出上锁,其实就是 Redis 的 set 操作的过程。
任务执行的入口,可以参考 net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor:
首先判断 lock 是否可用,然后再执行任务 task.call()。
作者:zhaoyh
来源链接:
http://zhaoyh.com.cn/2020/09/22/Spring%20Boot(%E5%85%AB)%E4%B9%8B%E5%AE%9A%E6%97%B6%E4%BB%BB%E5%8A%A1%E9%94%81Shedlock/#more
Original: https://www.cnblogs.com/suizhikuo/p/16264185.html
Author: 勤学如春起之苗
Title: 【SpringBoot实战】分布式定时任务锁Shedlock
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/539720/
转载文章受原作者版权保护。转载请注明原作者出处!