Redis分布式锁代码实现(Java)
![在这里插入图片描述](https://img-blog.csdnimg.cn/1b80116c93cb4825abe6b1c4dba4a9dd.webp#pic_center)
public class RedisLock {
public static Boolean getLock(RedisTemplate redisTemplate, String key, String value, long timeout) {
Boolean lock = redisTemplate.opsForValue().setIfAbsent(key,value,timeout,TimeUnit.SECONDS);
return lock;
}
public static void closeLock(RedisTemplate redisTemplate,String key, String value) {
while (true) {
redisTemplate.watch(key);
String revalue=String.valueOf(redisTemplate.opsForValue().get(key));
if (value.equalsIgnoreCase(revalue)) {
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.multi();
redisTemplate.delete(key);
List<Object> rlist = redisTemplate.exec();
if (rlist == null) {
continue;
}
}
redisTemplate.unwatch();
break;
}
}
}