一文詳解分布式鎖的看門狗機制
我們今天來看看這個 Redis 的看門狗機制,畢竟現在還是有很多是會使用 Redis 來實現分布式鎖的,我們現在看看這個 Redis 是怎么實現分布式鎖的,然后我們再來分析這個 Redis 的看門狗機制,如果沒有這個機制,很多使用 Redis 來做分布式鎖的小伙伴們,經常給導致死鎖。
Redis 實現分布式鎖
Redis實現分布式鎖,最主要的就是這幾個條件
獲取鎖
- 互斥:確保只能有一個線程獲取鎖
- 非阻塞:嘗試一次,成功返回true,失敗返回false
釋放鎖
- 手動釋放
- 超時釋放:獲取鎖時添加一個超時時間
上代碼:
@Resource
private RedisTemplate redisTemplate;
public static final String UNLOCK_LUA;
/**
* 釋放鎖腳本,原子操作
*/
static {
StringBuilder sb = new StringBuilder();
sb.append("if redis.call(\"get\",KEYS[1]) == ARGV[1] ");
sb.append("then ");
sb.append(" return redis.call(\"del\",KEYS[1]) ");
sb.append("else ");
sb.append(" return 0 ");
sb.append("end ");
UNLOCK_LUA = sb.toString();
}
/**
* 獲取分布式鎖,原子操作
* @param lockKey
* @param requestId 唯一ID, 可以使用UUID.randomUUID().toString();
* @param expire
* @param timeUnit
* @return
*/
public boolean tryLock(String lockKey, String requestId, long expire, TimeUnit timeUnit) {
try{
RedisCallback<Boolean> callback = (connection) -> {
return connection.set(lockKey.getBytes(Charset.forName("UTF-8")), requestId.getBytes(Charset.forName("UTF-8")), Expiration.seconds(timeUnit.toSeconds(expire)), RedisStringCommands.SetOption.SET_IF_ABSENT);
};
return (Boolean)redisTemplate.execute(callback);
} catch (Exception e) {
log.error("redis lock error.", e);
}
return false;
}
/**
* 釋放鎖
* @param lockKey
* @param requestId 唯一ID
* @return
*/
public boolean releaseLock(String lockKey, String requestId) {
RedisCallback<Boolean> callback = (connection) -> {
return connection.eval(UNLOCK_LUA.getBytes(), ReturnType.BOOLEAN ,1, lockKey.getBytes(Charset.forName("UTF-8")), requestId.getBytes(Charset.forName("UTF-8")));
};
return (Boolean)redisTemplate.execute(callback);
}
/**
* 獲取Redis鎖的value值
* @param lockKey
* @return
*/
public String get(String lockKey) {
try {
RedisCallback<String> callback = (connection) -> {
return new String(connection.get(lockKey.getBytes()), Charset.forName("UTF-8"));
};
return (String)redisTemplate.execute(callback);
} catch (Exception e) {
log.error("get redis occurred an exception", e);
}
return null;
}
這種實現方式就是相當于我們直接使用 Redis 來自己實現的分布式鎖,但是也不是沒有框架給我們來實現,那就是Redission。而看門狗機制是Redission提供的一種自動延期機制,這個機制使得Redission提供的分布式鎖是可以自動續(xù)期的。
為什么需要看門狗機制
分布式鎖是不能設置永不過期的,這是為了避免在分布式的情況下,一個節(jié)點獲取鎖之后宕機從而出現死鎖的情況,所以需要個分布式鎖設置一個過期時間。但是這樣會導致一個線程拿到鎖后,在鎖的過期時間到達的時候程序還沒運行完,導致鎖超時釋放了,那么其他線程就能獲取鎖進來,從而出現問題。
所以,看門狗機制的自動續(xù)期,就很好地解決了這一個問題。
Redisson已經幫我們實現了這個分布式鎖,我們需要的就是調用,那么我們來看看 Redisson 的源碼,他是如何來實現看門狗機制的。
tryLock
RedissonLock類下:
public boolean tryLock(long waitTime, TimeUnit unit) throws InterruptedException {
return tryLock(waitTime, -1, unit);
}
- waitTime:獲取鎖的最大等待時間(沒有傳默認為-1)
- leaseTime:鎖自動釋放的時間(沒有傳的話默認-1)
- unit:時間的單位(等待時間和鎖自動釋放的時間單位)
@Override
public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
long time = unit.toMillis(waitTime);
long current = System.currentTimeMillis();
long threadId = Thread.currentThread().getId();
Long ttl = tryAcquire(waitTime, leaseTime, unit, threadId);
// lock acquired
if (ttl == null) {
return true;
}
time -= System.currentTimeMillis() - current;
if (time <= 0) {
acquireFailed(waitTime, unit, threadId);
return false;
}
current = System.currentTimeMillis();
RFuture<RedissonLockEntry> subscribeFuture = subscribe(threadId);
if (!subscribeFuture.await(time, TimeUnit.MILLISECONDS)) {
if (!subscribeFuture.cancel(false)) {
subscribeFuture.onComplete((res, e) -> {
if (e == null) {
unsubscribe(subscribeFuture, threadId);
}
});
}
acquireFailed(waitTime, unit, threadId);
return false;
}
try {
time -= System.currentTimeMillis() - current;
if (time <= 0) {
acquireFailed(waitTime, unit, threadId);
return false;
}
while (true) {
long currentTime = System.currentTimeMillis();
ttl = tryAcquire(waitTime, leaseTime, unit, threadId);
// lock acquired
if (ttl == null) {
return true;
}
time -= System.currentTimeMillis() - currentTime;
if (time <= 0) {
acquireFailed(waitTime, unit, threadId);
return false;
}
// waiting for message
currentTime = System.currentTimeMillis();
if (ttl >= 0 && ttl < time) {
subscribeFuture.getNow().getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
} else {
subscribeFuture.getNow().getLatch().tryAcquire(time, TimeUnit.MILLISECONDS);
}
time -= System.currentTimeMillis() - currentTime;
if (time <= 0) {
acquireFailed(waitTime, unit, threadId);
return false;
}
}
} finally {
unsubscribe(subscribeFuture, threadId);
}
// return get(tryLockAsync(waitTime, leaseTime, unit));
}
上面這一段代碼最主要的內容講述看門狗機制的實際上應該算是 tryAcquire
最終落地為tryAcquireAsync
//如果獲取鎖失敗,返回的結果是這個key的剩余有效期
RFuture<Long> ttlRemainingFuture = this.tryLockInnerAsync(waitTime, this.commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);
//上面獲取鎖回調成功之后,執(zhí)行這代碼塊的內容
ttlRemainingFuture.onComplete((ttlRemaining, e) -> {
//不存在異常
if (e == null) {
//剩余有效期為null
if (ttlRemaining == null) {
//這個函數是解決最長等待有效期的問題
this.scheduleExpirationRenewal(threadId);
}
}
});
return ttlRemainingFuture;
調用tryLockInnerAsync,如果獲取鎖失敗,返回的結果是這個key的剩余有效期,如果獲取鎖成功,則返回null。
獲取鎖成功后,如果檢測不存在異常并且獲取鎖成功(ttlRemaining == null)。
那么則執(zhí)行this.scheduleExpirationRenewal(threadId);來啟動看門狗機制。
看門狗機制提供的默認超時時間是30*1000毫秒,也就是30秒
如果一個線程獲取鎖后,運行程序到釋放鎖所花費的時間大于鎖自動釋放時間(也就是看門狗機制提供的超時時間30s),那么Redission會自動給redis中的目標鎖延長超時時間。
在Redission中想要啟動看門狗機制,那么我們就不用獲取鎖的時候自己定義leaseTime(鎖自動釋放時間)。
但是 Redisson 和我們自己定義實現分布式鎖不一樣,如果自己定義了鎖自動釋放時間的話,無論是通過lock還是tryLock方法,都無法啟用看門狗機制。
所以你了解分布式鎖的看門狗機制了么?