Skip to main content
 首页 » 数据库

Redis重试锁

2022年07月18日154三少
@Value("${get.lock.max.time}")
private Integer getLockMax;

@Value("${get.lock.sleep}")
private Long getLockSleep;

@Resource
private RedisTemplate<String, Object> redisTemplate;

/**
* @desc : 加锁
* lockKey:加锁的key retryTimes:重试次数 expireTime:加锁有效期(单位:毫秒)
* @create: 2021/4/1 14:54:00
**/
@Override
public void addLock(String lockKey, Integer retryTimes,Long expireTime) {
if (retryTimes.equals(getLockMax)) {
log.warn("达到最大重试次数:{},获取锁失败", getLockMax);
throw new BusinessException(CloudWalkErrorCodeEnum.PET_GET_LOCK_ERROR);
}
log.info("开始加锁:{},retryTime:{}", lockKey, retryTimes);
Long increment = this.increment(lockKey, 1L, expireTime);
if (increment > 1) {
try {
Thread.sleep(getLockSleep);
} catch (InterruptedException e) {
log.error("休眠异常:{}", e);
Thread.currentThread().interrupt();
}
retryTimes++;
log.info("加锁失败", retryTimes);
addLock(lockKey, retryTimes,expireTime);
} else {
log.info("加锁成功");
}

}


/**
* @desc : 释放锁
* @create: 2021/4/1 14:54:00
**/
@Override
public void unLock(String lockKey) {
log.info("释放锁:{}", lockKey);
this.delete(lockKey);
log.info("释放锁成功");
}


@Override
public Long increment(String key, long delta, Long expireTime) {
log.info("increment key: {}", key);
Long current = redisTemplate.opsForValue().increment(key, delta);
if(expireTime != null) {
expire(key, expireTime);
}
return current;
}

@Override
public void delete(String key) {
log.info("delete key: {}", key);
redisTemplate.delete(key);
}

本文参考链接:https://www.cnblogs.com/maohuidong/p/14606529.html