在我们业务开发过程中,经常会有需求做一些定时任务,但是由于定时任务的特殊性,以及一些方法的幂等性要求,在分布式多节点部署的情况下,某个定时任务只需要执行一次。
1. 背景介绍
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 从严格意义上来说不是一个分布式任务调度框架,而是一个分布式锁。所谓的分布式锁,解决的核心问题就是各个节点中无法通信的痛点。各个节点并不知道这个定时任务有没有被其他节点的定时器执行,所以理论上只需要有一个各个节点都能够访问到的资源,用这个资源去标记这个定时任务有没有执行就可以了。
[1]2.
Shedlock 实现
Shedlock 实现分布式锁,可以依赖如下组件:
本文主要以来 Redis 为公共存储,实现定时任务的分布式锁。首先,我们假设你的 Spring Boot 项目已经引入了
Redis,在项目的 pom 文件中加入依赖:
-
加载中,请稍候......