集群服务器下使用SpringBoot @Scheduled注解定时任务

时间:2023-03-09 06:40:16
集群服务器下使用SpringBoot @Scheduled注解定时任务

原文:https://blog.****.net/huyang1990/article/details/78551578

SpringBoot提供了 Schedule模块完美支持定时任务的执行

在实际开发中由于项目部署在分布式或集群服务器上 会导致定时任务多次触发

因此,使用redis分布锁机制可以有效避免多次执行定时任务

核心方法是org.springframework.data.redis.core包下的

setIfAbsent() 方法 返回值为布尔类型

方法类似redis的SETNX命令 即”SET if Not Exists”

服务器在执行邮件定时发送任务之前会向redis缓存中写入lock_key即任务锁 表明此服务器正在执行定时任务

另一台服务器在写入锁时 由于锁已经存在就不做任何操作

执行定时任务的服务器在执行完成后需释放任务锁

@Scheduled(cron = "${scheduled.cron}")
public void scheduler(){
try {
if (redisUtil.get("key") == null) {
if(redisUtil.setScheduler("key", "value")){ //定时任务执行代码
Thread.sleep(3000);
}
}
} catch (InterruptedException e) {
logger.error("定时任务异常");
}finally{
redisUtil.remove("key");
}
}

RedisUtils.java

public boolean setScheduler(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
return operations.setIfAbsent(key, value);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}