在定时任务中添加时间锁,可以防止集群中不同机器重复执行此定时任务:
@Scheduled(cron = "*/5 * * * * ? ")
void missedCallsPush() {
/**
* 时间锁
*/
if(!getLock(IM_TIME_LOCK, false)){
return;
}
时间锁代码实现:
/**
* lock
* @param key key
* @return boolean true分钟维度/false 秒钟维度
*/
private boolean getLock(String key, Boolean lockMinute) {
String currentTime;
Date now = new Date();
if (lockMinute) {
currentTime = DateUtil.getDateStrMin(now); //Date转String
} else {
currentTime = DateUtil.getDateStrSec(now);
}
String lock = RedisHandle.getInstance().getSet(key, currentTime);
return !currentTime.equals(lock);
}
原理
只有当A执行此定时任务时,A的currentTime才会和redis中取出的lock不同。而在A开始执行此定时任务时,B取出的lock其实就是currentTime。因此可以保证集群中的不同机器不会重复执行此定时任务。