【SpringBoot实战】分布式定时任务锁Shedlock
在我们业务开发过程中,经常会有需求做一些定时任务,但是由于定时任务的特殊性,以及一些方法的幂等性要求,在分布式多节点部署的情况下,某个定时任务只需要执行一次。
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 文件中加入依赖:
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
4.14.0
</dependency>
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-redis-spring</artifactId>
4.14.0
</dependency>
开启定时任务锁:
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor ="PT30S")
public class ShedlockConfig {
@Bean
public LockProvider lockProvider(RedisTemplate redisTemplate) {
returnnewRedisLockProvider(redisTemplate.getConnectionFactory());
}
}
“
defaultLockAtMostFor = “PT30S” 表示默认锁的最大占用时间是 30s;
”
其次,在定时任务方法上,加上注解 @SchedulerLock:
/**
* 通过设置lockAtMostFor,我们可以确保即使节点死亡,锁也会被释放;
* 通过设置lockAtLeastFor,我们可以确保它在30s内不会执行超过一次;
*/
@Scheduled(cron ="00 12 15 22 * ?")
@SchedulerLock(name ="testTask-1", lockAtMostFor ="30s", lockAtLeastFor ="10s")
public void testTask1() {
LockAssert.assertLocked();
log.info("exec testTask1......");
}
@Scheduled(fixedRate =10000L)
@SchedulerLock(name ="testTask-2", lockAtMostFor ="10s", lockAtLeastFor ="2s")
public void testTask2() {
LockAssert.assertLocked();
log.info("exec testTask2......");
}
启动多个节点,会发现,每次定时任务只有一个节点执行,定时任务执行后,在 Redis 里会看到两个 key:job-lock:default:testTask-1 和 job-lock:default:testTask-2。
Shedlock 通过 AOP,拿到 TaskScheduler 的行为做代理,并加入分布式锁实现所需要的功能。
上锁入口在 RedisLockProvider.java:
@NonNull
public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {
String key = this.buildKey(lockConfiguration.getName());
Expiration expiration = getExpiration(lockConfiguration.getLockAtMostUntil());
returnBoolean.TRUE.equals(tryToSetExpiration(this.redisTemplate, key, expiration, SetOption.SET_IF_ABSENT)) ? Optional.of(newRedisLockProvider.RedisLock(key, this.redisTemplate, lockConfiguration)) : Optional.empty();
}
private static Boolean tryToSetExpiration(StringRedisTemplate template, String key, Expiration expiration, SetOption option) {
return(Boolean)template.execute((connection) -> {
byte[] serializedKey = template.getKeySerializer().serialize(key);
byte[] serializedValue = template.getValueSerializer().serialize(String.format("ADDED:%s@%s", Utils.toIsoString(ClockProvider.now()), Utils.getHostname()));
returnconnection.set(serializedKey, serializedValue, expiration, option);
},false);
}
可以看出上锁,其实就是 Redis 的 set 操作的过程。
任务执行的入口,可以参考 net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor:
@Override
@NonNull
public <T> TaskResult<T> executeWithLock(@NonNull TaskWithResult<T> task, @NonNull LockConfiguration lockConfig) throws Throwable {
Optional<SimpleLock> lock = lockProvider.lock(lockConfig);
String lockName = lockConfig.getName();
if(alreadyLockedBy(lockName)) {
logger.debug("Already locked '{}'", lockName);
returnTaskResult.result(task.call());
}elseif(lock.isPresent()) {
try {
LockAssert.startLock(lockName);
logger.debug("Locked '{}', lock will be held at most until {}", lockName, lockConfig.getLockAtMostUntil());
returnTaskResult.result(task.call());
} finally {
LockAssert.endLock();
lock.get().unlock();
if(logger.isDebugEnabled()) {
Instant lockAtLeastUntil = lockConfig.getLockAtLeastUntil();
Instant now = ClockProvider.now();
if(lockAtLeastUntil.isAfter(now)) {
logger.debug("Task finished, lock '{}' will be released at {}", lockName, lockAtLeastUntil);
}else{
logger.debug("Task finished, lock '{}' released", lockName);
}
}
}
}else{
logger.debug("Not executing '{}'. It's locked.", lockName);
returnTaskResult.notExecuted();
}
}
首先判断 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