用redis setnx 处理
@Scheduled(cron = "0/5 * * * * ? ")
public void schedutest3(){
log.info("定时任务开始");
Long setnx = RedisShardedPoolUtil.setnx(CLOSE_ORDER_TASK_LOCK, String.valueOf(System.currentTimeMillis()));
if (setnx != null && setnx.intValue() == 1){
RedisShardedPoolUtil.expire(CLOSE_ORDER_TASK_LOCK,5);
log.info("获得{},threadname:{}",CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
RedisShardedPoolUtil.del(CLOSE_ORDER_TASK_LOCK);
log.info("释放{},threadname:{}",CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
}else {
log.info("没有获得分布式锁:{}",CLOSE_ORDER_TASK_LOCK);
}
log.info("定时任务结束");
}
加上对时间戳的判断进行处理(多个进程deBug看一下)
@Scheduled(cron = "0/5 * * * * ? ")
public void schedutest4(){
log.info("定时任务开始");
Long setnx = RedisShardedPoolUtil.setnx(CLOSE_ORDER_TASK_LOCK, String.valueOf(System.currentTimeMillis()));
if (setnx != null && setnx.intValue() == 1){
RedisShardedPoolUtil.expire(CLOSE_ORDER_TASK_LOCK,5);
log.info("获得{},threadname:{}",CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
RedisShardedPoolUtil.del(CLOSE_ORDER_TASK_LOCK);
log.info("释放{},threadname:{}",CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
}else {
//没有获取到锁,继续判断,比较时间戳,看是否可以获取到锁
String lockvalue = RedisShardedPoolUtil.get(CLOSE_ORDER_TASK_LOCK);
if (lockvalue != null && System.currentTimeMillis() > Long.parseLong(lockvalue)){
//再次用当前时间戳getset。
//返回给定的key的旧值,->旧值判断,是否可以获取锁
//当key没有旧值时,即key不存在时,返回nil ->获取锁
//这里我们set了一个新的value值,获取旧的值。
String getSetResult = RedisShardedPoolUtil.getSet(CLOSE_ORDER_TASK_LOCK, String.valueOf(System.currentTimeMillis()));
if (getSetResult == null || (getSetResult != null && StringUtils.equals(lockvalue,getSetResult))){
RedisShardedPoolUtil.expire(CLOSE_ORDER_TASK_LOCK,5);
log.info("获得{},threadname:{}",CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
RedisShardedPoolUtil.del(CLOSE_ORDER_TASK_LOCK);
log.info("释放{},threadname:{}",CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
}else {
log.info("没有获得分布式锁:{}",CLOSE_ORDER_TASK_LOCK);
}
}else {
log.info("没有获得分布式锁:{}",CLOSE_ORDER_TASK_LOCK);
}
}
log.info("定时任务结束");
}