public class RedissonDistributedLock {
private static final Logger LOGGER = LoggerFactory.getLogger(RedissonDistributedLock.class);
private RedisTemplate<Serializable, Serializable> redisTemplate;
public void setRedisTemplate(RedisTemplate<Serializable, Serializable> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public JsonResult synchronize(String lockName, LockSupplier<JsonResult> lockSupplier) {
String key = "LOCK" + lockName;
boolean result = tryLock(key, 1, 5000L, TimeUnit.MILLISECONDS);
if (!result) {
// 超时时间
Long expire = redisTemplate.getExpire(key);
if (expire.equals(-1L)){
// 补充过期时间
redisTemplate.expire(key, 5000L, TimeUnit.MILLISECONDS);
}
LOGGER.info(key + "请勿重复操作");
return new JsonResult(false, "请勿重复操作");
}
try {
return lockSupplier.run();
} catch (Exception e){
LOGGER.error("锁lockName=" + lockName + "异常", e);
throw new MyException(e.getMessage());
}finally {
deleteLock(key);
}
}
/**
* 创建锁
* @param lockKey
* @param value
* @param releaseTime
* @return
*/
public boolean tryLock(String lockKey, int value, long releaseTime, TimeUnit timeUnit) {
Boolean store = redisTemplate.opsForValue().setIfAbsent(lockKey,value);
if(null != store && store){
redisTemplate.expire(lockKey,releaseTime, timeUnit);
return true;
}
LOGGER.error("redis加锁时,setIfAbsent返回值异常,返回值是" + store);
return false;
}
/**
* 删除锁
* @param key
*/
public void deleteLock(String key) {
redisTemplate.delete(key);
}
}
网友评论