public Boolean acquireLock(String redisKey, Long expiredMillis) {
Boolean acquired = false;
//设置value防止expire失败
long value = System.currentTimeMillis() + expiredMillis;
try {
boolean locked = redisTemplate.opsForValue().setIfAbsent(redisKey, value);
//setNx失败
if(!locked) {
Long oldValue = (Long)redisTemplate.opsForValue().get(redisKey);
if(oldValue !=null && oldValue < System.currentTimeMillis()) {
// 超时时使用getset进行比较,防止多个线程获取锁
Long getValue = (Long)redisTemplate.opsForValue().getAndSet(redisKey, value);
if(getValue !=null && getValue.equals(oldValue)) {
//超时则获取锁
redisTemplate.expire(redisKey,expiredMillis, TimeUnit.MILLISECONDS);
acquired = true;
}
}
} else {
redisTemplate.expire(redisKey,expiredMillis, TimeUnit.MILLISECONDS);
acquired = true;
}
} catch (Exception e) {
log(...);
acquired = true;
}
return acquired;
}
@Override
public Boolean freeLock(String redisKey) {
Boolean free = false;
try {
Long getValue = (Long)redisTemplate.opsForValue().get(redisKey);
//防止删除不属于自己的锁
if(getValue != null && System.currentTimeMillis() < getValue) {
redisTemplate.delete(redisKey);
free = true;
}
} catch (Exception e) {
log(...);
}
return free;
}