可重入性是指線程在持有鎖的情況下再次請求加鎖,如果一個鎖支持同一個線程的多次加鎖,那麼這個鎖就是可重入的。比如 Java 語言裏有個 ReentrantLock 就是可重入鎖。如果Redis 分佈式鎖要支持可重入,需要對客戶端的 set 方法進行包裝,使用線程的 Threadlocal 變量存儲當前持有鎖的計數。
代碼如下:
public class RedisWithReentrantLock {
private ThreadLocal<Map<String, Integer>> lockers = new ThreadLocal<>();
private Jedis jedis;
public RedisWithReentrantLock(Jedis jedis) {
this.jedis = jedis;
}
private boolean _lock(String key){
return jedis.set(key, "", "nx", "ex", 5L) != null;
}
private void _unlock(String key){
jedis.del(key);
}
private Map<String, Integer> currentLockers(){
Map<String, Integer> refs = lockers.get();
if (null != refs){
return refs;
}
lockers.set(new HashMap<>());
return lockers.get();
}
public boolean lock(String key){
Map<String, Integer> refs = currentLockers();
Integer refCnt = refs.get(key);
if (null != refCnt){
refs.put(key, refCnt + 1);
return true;
}
boolean ok = this._lock(key);
if (!ok){
return false;
}
refs.put(key, 1);
return true;
}
public boolean unlock(String key){
Map<String, Integer> refs = currentLockers();
Integer refCnt = refs.get(key);
if (null == refCnt){
return false;
}
refCnt -= 1;
if (refCnt > 0){
refs.put(key, refCnt);
}else {
refs.remove(key);
this._lock(key);
}
return true;
}
/**
public static void main(String[] args) {
Jedis jedis = new Jedis("localhost");
RedisWithReentrantLock redisWithReentrantLock = new RedisWithReentrantLock(jedis);
System.out.println(redisWithReentrantLock.lock("TestLock"));
System.out.println(redisWithReentrantLock.lock("TestLock"));
System.out.println(redisWithReentrantLock.unlock("TestLock"));
System.out.println(redisWithReentrantLock.unlock("TestLock"));
}
**/
}