redisTemplate实现
@Autowired
private StringRedisTemplate redisTemplate;
@SneakyThrows(InterruptedException.class)
public Boolean tryLock(String lockKey, String value, long waitTime, long expireTime, TimeUnit timeUnit) {
String waitKey = UUID.randomUUID().toString();
expireSet(waitKey, waitKey, waitTime, timeUnit);
Boolean aBoolean;
do {
aBoolean = lock(lockKey, value, expireTime, timeUnit);
if (BooleanUtils.isTrue(aBoolean)) {
break;
}
Thread.sleep(500);
} while (hasKey(waitKey));
delete(waitKey);
return aBoolean;
}
public Boolean lock(String lockKey, String value, long expireTime, TimeUnit timeUnit) {
return redisTemplate.opsForValue().setIfAbsent(lockKey, value, expireTime, timeUnit);
}
public Boolean unlock(String key, String value) {
String currentValue = get(key);
Boolean result = false;
if (StringUtils.equals(currentValue, value)) {
result = delete(key);
}
return result;
}
public boolean hasKey(String key) {
return Boolean.TRUE.equals(redisTemplate.hasKey(key));
}
public Boolean delete(String key) {
return redisTemplate.opsForValue().getOperations().delete(key);
}
public void expireSet(String key, String value, long expireTime, TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, expireTime, timeUnit);
}
public String get(String key) {
return redisTemplate.opsForValue().get(key);
}
redisson实现
@Autowired
private RedissonClient redissonClient;
RLock rLock = redissonClient.getLock("my_key");
boolean lock = rLock.tryLock(30, 30, TimeUnit.SECONDS);
if (lock){
try {
}finally {
rLock.unlock();
}
}