public class RedisReentrantLock {
private static final String script =
"if (ARGV[1] = redis.call('get', KEYS[1])) " +
"then " +
"redis.call('del', KEYS[1]) " +
"return 1; " +
"else " +
"return 0; " +
"end";
private static final ThreadLocal<Map<String, Integer>> tl = ThreadLocal.withInitial(HashMap::new);
private static final Map<String, String> valueCache = new HashMap<>();
private static final String cacheKeyPatten = "threadId-%d-%s";
private final Jedis jedis;
public RedisReentrantLock(Jedis jedis) {
this.jedis = jedis;
}
private Map<String, Integer> getLocks() {
return tl.get();
}
public void unLock(String key) {
//key集合
Map<String, Integer> locks = getLocks();
//若存在重入,就减小
Integer num = locks.get(key);
if (num > 1) {
locks.computeIfPresent(key, (k, v) -> --v);
}else {
//不存在重入,删除key
String value = valueCache.get(String.format(cacheKeyPatten, Thread.currentThread().getId(), key));
tryLock(key,value);
locks.remove(key);
}
}
public void tryLock(String key, String value) {
jedis.eval(script, 1, key, value);
}
public boolean lock(String key, long timeout, TimeUnit timeUnit) {
return lock(key, 5, TimeUnit.SECONDS, timeout, timeUnit);
}
public boolean lock(String key, long redisKeyTimeout, TimeUnit cacheKeyTimeUnit, long timeout, TimeUnit timeUnit) {
//检查本地是否已存在
Map<String, Integer> locks = getLocks();
if (locks.containsKey(key)) {
locks.computeIfPresent(key, (k, v) -> ++v);
return true;
} else {
long endTime = System.currentTimeMillis() + timeUnit.toMillis(timeout);
String uuid = UUID.randomUUID().toString();
while (true) {
//尝试获取锁
if (tryLock(key, uuid, cacheKeyTimeUnit.toSeconds(redisKeyTimeout))) {
locks.put(key, 1);
//缓存redis中的value,在释放锁的时候检查是否是同一把锁
valueCache.put(String.format(cacheKeyPatten, Thread.currentThread().getId(), key), uuid);
return true;
}
//获取锁超时
if (System.currentTimeMillis() > endTime) {
return false;
}
//等待500ms
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public boolean tryLock(String key,String value, long timeout) {
String ret = jedis.set(key, value, "nx", "ex", timeout);
return null != ret;
}
}
可重入分布式锁-redis实现
最新推荐文章于 2024-09-08 21:36:17 发布
这个博客介绍了如何使用Redis实现一个可重入锁。通过Java代码展示了如何使用Jedis客户端进行加锁、解锁操作,并且包含重试机制以防止锁超时。还涉及到本地缓存来处理重入情况,并使用Lua脚本来保证原子性操作。
摘要由CSDN通过智能技术生成