Redis分布式锁原理解析

  • 时间:
  • 浏览:0
  • 来源:跟我学网络

最后发布:2018-08-14 15:44:04首次发布:2018-08-14 15:44:04


@Scheduled(cron = "0 */1 * * * ?")
public void closeOrderTask() {
	log.info("关闭订单定时任务启动");
	long lockTimeOut = Long.parseLong(PropertiesUtil.getProperty("lock.timeout","5000"));
	Long setnxResult = RedisShardedPoolUtil.setnx(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK, String.valueOf(System.currentTimeMillis() + lockTimeOut));
	if (setnxResult != null && setnxResult.intValue() == 1) {
		closeOrder(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
	} else {
		
		String lockValueA = RedisShardedPoolUtil.get(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
		if (lockValueA != null && System.currentTimeMillis() > Long.parseLong(lockValueA)) {
			String lockValueB = RedisShardedPoolUtil.getSet(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK, String.valueOf(System.currentTimeMillis() + lockTimeOut));
			
			
			
			
			if (lockValueB == null || (lockValueB != null && StringUtils.equals(lockValueA, lockValueB))) {
				
				closeOrder(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
			} else {
				log.info("没有获取到分布式锁:{}", Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
			}
		} else {
			log.info("没有获取到分布式锁:{}", Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
		}
	}
	log.info("关闭订单定时任务结束");
}
 private void closeOrder(String lockName) {
        RedisShardedPoolUtil.expire(lockName, 5);
        log.info("获取{},ThreadName:{}", Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK, Thread.currentThread().getName());
        int hour = Integer.parseInt(PropertiesUtil.getProperty("close.order.task.time.out", "2"));
        iOrderService.closeOrder(hour);
        RedisShardedPoolUtil.del(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
        log.info("释放{},ThreadName:{}", Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK, Thread.currentThread().getName());

        log.info("********************************************");
    }

点击进入GitHub 查看代码