SpringBoot使用@Scheduled 和 Redis分布式锁实现分布式定时任务
warning:
这篇文章距离上次修改已过202天,其中的内容可能已经有所变动。
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Component
public class DistributedScheduledTask {
private final RedissonClient redissonClient;
public DistributedScheduledTask(RedissonClient redissonClient) {
this.redissonClient = redissonClient;
}
@Scheduled(fixedRate = 60000) // 每分钟执行一次
public void scheduleTask() {
// 使用Redisson提供的锁机制实现分布式锁
RLock lock = redissonClient.getLock("scheduledTaskLock");
try {
// 尝试加锁,最多等待10秒,锁超时10秒自动释放
if (lock.tryLock(10, 10, TimeUnit.SECONDS)) {
// 加锁成功,执行任务逻辑
System.out.println("执行定时任务...");
// 这里放置定时任务的具体执行逻辑
} else {
System.out.println("无法获取锁,任务被跳过...");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// 处理异常情况
} finally {
// 释放锁
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}
这段代码使用了Redisson提供的RedLock机制来实现分布式锁,确保了即使在多实例的环境下,同一时间只有一个实例执行定时任务。这是一个简化的例子,实际应用中你需要将System.out.println
替换为具体的业务逻辑,并处理好异常情况。
评论已关闭