【Redis實戰五】Redisson鎖機制源碼分析
1、了解分布式鎖的特性
1、鎖的互斥性
也就是說,在任意時刻,只能有一個客戶端能獲取到鎖,不能同時有兩個或多個客戶端獲取到鎖。
簡單來說,就比如上廁所,一個廁所只有一個坑位,只能一個人上,不能同時兩個人或多個人上。
2、鎖的同一性
也就是說,鎖只能被持有該鎖的客戶端進行刪除(釋放鎖),不能由其他客戶端刪除。
簡單倆說,就是誰加的鎖,就只能誰來解鎖。也就是解鈴還須系鈴人。
3、鎖的可重入性
也就是說,持有某個鎖的客戶端,可以繼續對該鎖進行加鎖,實現鎖的續租。
簡單來說,就是你上廁所的按時間收費的,時間快到了會按照時間給你續租,而會給你價錢。
而Redisson則會增大的你的續租次數,也就是可重入次數。但絕不收費,因為Redis是開源的嘛。
4、鎖的容錯性
鎖超過了最大續租時間后,會自動釋放鎖,其他客戶端會繼續獲得該鎖,從而防止死鎖的發生。
簡單來說,比如你上個廁所上了五小時,廁管員覺得不對勁,就來測試,發現你悄悄逃票了,此時測試會自動變成解鎖狀態,其他人就可以去上了,只是廁管員血虧5塊大洋。
2、帶著幾個特性去看Redisson源碼
先回顧一下Redisson加解鎖代碼如何寫的
public TestEntity getById2(Long id){
RLock lock = redissonClient.getLock("demo2_lock");
lock.lock(20, TimeUnit.SECONDS);
index++;
log.info("current index is : {}", index);
TestEntity testEntity = new TestEntity(new Random().nextLong(), UUID.randomUUID().toString(), new Random().nextInt(20) + 10);
log.info("模擬查詢數據庫:{}", testEntity);
lock.unlock();
return testEntity;
}
2.1、關注Redisson.getLock()方法
@Override
public RLock getLock(String name) {
return new RedissonLock(commandExecutor, name);
}
其實就是創建一個RedissonLock對象, 所以加鎖的邏輯就在RedissonLock.lock()中,解鎖的邏輯就在RedissonLock.unlock()。
2.2、關注RedissonLock.lock()方法
// RedissonLock.lock()的方法體
public void lock(long leaseTime, TimeUnit unit) {
try {
// 調用了lock的重載方法
lock(leaseTime, unit, false);
} catch (InterruptedException e) {
throw new IllegalStateException();
}
}
關注lock的重載方法
// leaseTime表示最大續時間,unit表示續約時間單位,interruptibly表示是否可以中斷
private void lock(long leaseTime, TimeUnit unit, boolean interruptibly) throws InterruptedException {
// 獲取當前線程的線程ID
long threadId = Thread.currentThread().getId();
// 嘗試獲取鎖,結果為null表示此時沒有客戶端占用鎖,絕不矯情,直接拿到鎖就返回。
// 結果ttl>0的話,表示此時已經有了其他不識好歹的客戶端暫用了鎖,那么就只能絕望的等待了
Long ttl = tryAcquire(-1, leaseTime, unit, threadId);
// lock acquired
if (ttl == null) {
return;
}
// 等待時訂閱一個渠道,如果鎖被其他客戶端釋放了,會通過發布訂閱模式在publish上發一個消息,表示鎖已經釋放了
CompletableFuture<RedissonLockEntry> future = subscribe(threadId);
pubSub.timeout(future);
RedissonLockEntry entry;
if (interruptibly) {
entry = commandExecutor.getInterrupted(future);
} else {
entry = commandExecutor.get(future);
}
try {
// 我干等這不是辦法,我還是要不斷去嘗試看能不能獲取鎖
while (true) {
ttl = tryAcquire(-1, leaseTime, unit, threadId);
// 如果TTL為空了,表示獲取到了鎖,那還等什么,長驅直入就是。
if (ttl == null) {
// 結束循環等待
break;
}
// 如果ttl還是大于0的,表示其他客戶端真的是過于不識好歹,還不肯釋放鎖。但好歹還是說了它還要持有錯多久。
if (ttl >= 0) {
try {
// 既然如此,那么我就等待你的時間到達吧,除非我突然有啥事被中斷了,否則我就等到你過期
entry.getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// 如果傳入了中斷標識,直接拋出異常,中斷了,干別的事情去
if (interruptibly) {
throw e;
}
// 否則還是老老實實的繼續等待時間到來
entry.getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
}
}
// 鎖過期時間小于0, 表示那個殺千刀的客戶端居然沒有設置超時時間,它包場了,這可咋整。
else {
// 如果不被中斷,那么我也只有無期限的等待下去了,我不希望這個期限是一萬年
if (interruptibly) {
entry.getLatch().acquire();
} else {
entry.getLatch().acquireUninterruptibly();
}
}
}
} finally {
// 最后,不管如何,我無論如何都要去取消訂閱這個publish的消息,因為這會浪費我的精力,這已經是我最后的堅持了。
// 其實是釋放資源
unsubscribe(entry, threadId);
}
// get(lockAsync(leaseTime, unit));
}
關注tryAcquire加鎖方法
private Long tryAcquire(long waitTime, long leaseTime, TimeUnit unit, long threadId) {
return get(tryAcquireAsync(waitTime, leaseTime, unit, threadId));
}
該方法調用了tryAcquireAsync來實現的,所以我們關注tryAcquireAsync方法,繼續跟進。
關注tryAcquireAsync加鎖方法
private <T> RFuture<Long> tryAcquireAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId) {
RFuture<Long> ttlRemainingFuture;
// 首先判斷租約時間是否大于0
if (leaseTime > 0) {
// 大于零,調用tryLockInnerAsync獲取鎖
ttlRemainingFuture = tryLockInnerAsync(waitTime, leaseTime, unit, threadId, RedisCommands.EVAL_LONG);
} else {
// 否則,使用默認的租約時間 追溯下去發現private long lockWatchdogTimeout = 30 * 1000; 也就是30s的租約時間
ttlRemainingFuture = tryLockInnerAsync(waitTime, internalLockLeaseTime,
TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);
}
//
CompletionStage<Long> f = ttlRemainingFuture.thenApply(ttlRemaining -> {
// lock acquired
// 結果為空,如果leaseTime大于哦,更新internalLockLeaseTime為指定的超時時間,并且不會啟動看門狗(watch dog)
if (ttlRemaining == null) {
if (leaseTime > 0) {
internalLockLeaseTime = unit.toMillis(leaseTime);
} else {
// 使用定時任務,自動續約(使用看門狗(watch dog))
scheduleExpirationRenewal(threadId);
}
}
return ttlRemaining;
});
return new CompletableFutureWrapper<>(f);
}
可以看到,加鎖最終會調用tryLockInnerAsync進行加鎖,而續約會使用scheduleExpirationRenewal進行續約。
關注tryLockInnerAsync實現真正的加鎖邏輯
<T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
return evalWriteAsync(getRawName(), LongCodec.INSTANCE, command,
"if (redis.call('exists', KEYS[1]) == 0) then " +
"redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return nil; " +
"end; " +
"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
"redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return nil; " +
"end; " +
"return redis.call('pttl', KEYS[1]);",
Collections.singletonList(getRawName()), unit.toMillis(leaseTime), getLockName(threadId));
}
這里執行了一段lua腳本(整個lua腳本保障原子性),我們將腳本內容復制出來,詳細解釋一下。
-- KEYS[1] 加鎖的對象(也就是我們傳入的的鎖名稱)
-- ARGV[1] 表示鎖的過期時間
-- ARGV[2]:UUID+當前線程id
-- 如果鎖不存在。 == 0表示不存在 == 1表示存在
if (redis.call('exists', KEYS[1]) == 0) then
-- 對我自己的鎖執行一個incrby(自增,表示鎖的可重入次數)操作
redis.call('hincrby', KEYS[1], ARGV[2], 1);
-- 對key設置一個過期時間(過期時間就是保證鎖的容錯性)
redis.call('pexpire', KEYS[1], ARGV[1]);
-- 返回nil, 相當于null, 表示獲取鎖成功
return nil;
end ;
-- 繼續判斷鎖名成+UUID+當前線程id是否存在,其實就是判斷我自己有沒有已經拿到鎖(保證鎖的可重入性)
if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then
-- 自己已經持有鎖,執行一個incrby(自增,表示鎖的可重入次數)操作
redis.call('hincrby', KEYS[1], ARGV[2], 1);
-- 重新設置過期時間
redis.call('pexpire', KEYS[1], ARGV[1]);
-- 返回nil, 相當于null, 表示獲取鎖成功
return nil;
end ;
-- 都不是,表示已經有其他客戶端獲取到了鎖,此時返回key的過期時間,也就是別人釋放鎖的時間(但其他客戶端可能出現續約,存在會等待更久的可能)
return redis.call('pttl', KEYS[1]);
整個lua腳本保障原子性,從而只會有一個客戶端能夠獲取到鎖,這樣就保證了鎖的互斥性。
打一個斷點看獲取到的鎖信息
hash表中的第一個值表示UUID+線程ID,這二個值表示鎖的重入次數,如果鎖被多次獲取,那么這個值就是大于1。
關注scheduleExpirationRenewal實現自動續約
protected void scheduleExpirationRenewal(long threadId) {
ExpirationEntry entry = new ExpirationEntry();
ExpirationEntry oldEntry = EXPIRATION_RENEWAL_MAP.putIfAbsent(getEntryName(), entry);
// 不為空表示已經開啟了續約操作
if (oldEntry != null) {
oldEntry.addThreadId(threadId);
} else {
// 如果沒有開啟續約操作
entry.addThreadId(threadId);
try {
// 自動續約
renewExpiration();
} finally {
if (Thread.currentThread().isInterrupted()) {
cancelExpirationRenewal(threadId);
}
}
}
}
關注renewExpiration()方法
private void renewExpiration() {
ExpirationEntry ee = EXPIRATION_RENEWAL_MAP.get(getEntryName());
if (ee == null) {
return;
}
// 創建一個定時任務去實現自動續約
Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
// 獲取當前鎖的ExpirationEntry 對象。
ExpirationEntry ent = EXPIRATION_RENEWAL_MAP.get(getEntryName());
if (ent == null) {
return;
}
// 獲取第一個線程ID
Long threadId = ent.getFirstThreadId();
if (threadId == null) {
return;
}
// 鎖續期
CompletionStage<Boolean> future = renewExpirationAsync(threadId);
future.whenComplete((res, e) -> {
if (e != null) {
log.error("Can't update lock " + getRawName() + " expiration", e);
EXPIRATION_RENEWAL_MAP.remove(getEntryName());
return;
}
// 續約成功,遞歸自己無限續約下去
if (res) {
// reschedule itself
renewExpiration();
} else {
// 續約失敗,表示鎖已釋放,取消續約任務
cancelExpirationRenewal(null);
}
});
}
}, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS); // internalLockLeaseTime / 3表示每隔鎖時間的三分之一,去續約一次
ee.setTimeout(task);
}
關注renewExpirationAsync方法
protected CompletionStage<Boolean> renewExpirationAsync(long threadId) {
return evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return 1; " +
"end; " +
"return 0;",
Collections.singletonList(getRawName()),
internalLockLeaseTime, getLockName(threadId));
}
我們發現,又是一段lua腳本,還是復制出來,格式化后詳細解釋下代碼。
-- KEYS[1] 加鎖的對象(也就是我們傳入的的鎖名稱)
-- ARGV[1] 表示鎖的過期時間
-- ARGV[2]:UUID+當前線程id
-- 使用hexists判斷鎖是不是自己持有的, == 1表示是自己持有,== 0 表示被其他客戶端持有
if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then
-- 重新設置過期時間
redis.call('pexpire', KEYS[1], ARGV[1]);
-- 返回1 表示續約成功
return 1;
end ;
-- 返回0 表示續約失敗,也意味著鎖已經被釋放或者被其他客戶端獲取了
return 0;
所以續約的邏輯就是,啟動一個定時任務,每隔續約時間的三分之一次就執行一次。嘗試去續約,續約成功則會一直遞歸續約下去。續約失敗表示鎖已被釋放,則停止續約任務。
而續約的操作就是,判斷是否是自己持有鎖,是的話就重新設置過期時間,并且返回1表示續約成功,否則返回0表示續約失敗。
2.3、關注RedissonLock.unlock()方法
@Override
public void unlock() {
try {
// 其實就是調用了unlockAsync進行解鎖
get(unlockAsync(Thread.currentThread().getId()));
} catch (RedisException e) {
if (e.getCause() instanceof IllegalMonitorStateException) {
throw (IllegalMonitorStateException) e.getCause();
} else {
throw e;
}
}
// Future<Void> future = unlockAsync();
// future.awaitUninterruptibly();
// if (future.isSuccess()) {
// return;
// }
// if (future.cause() instanceof IllegalMonitorStateException) {
// throw (IllegalMonitorStateException)future.cause();
// }
// throw commandExecutor.convertException(future);
}
我們可以看到,會使用unlockAsync方法進行解鎖,并且在這里傳入了當前的線程ID。
關注unlockAsync方法
@Override
public RFuture<Void> unlockAsync(long threadId) {
// 調用unlockInnerAsync實現異步解鎖
RFuture<Boolean> future = unlockInnerAsync(threadId);
// 釋放之后再處理一些事情
CompletionStage<Void> f = future.handle((opStatus, e) -> {
// 取消(停止)續約任務,這里也會停止watch dog
cancelExpirationRenewal(threadId);
if (e != null) {
throw new CompletionException(e);
}
if (opStatus == null) {
IllegalMonitorStateException cause = new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: "
+ id + " thread-id: " + threadId);
throw new CompletionException(cause);
}
return null;
});
return new CompletableFutureWrapper<>(f);
}
關注解鎖的核心邏輯unlockInnerAsync方法
protected RFuture<Boolean> unlockInnerAsync(long threadId) {
return evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
"return nil;" +
"end; " +
"local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
"if (counter > 0) then " +
"redis.call('pexpire', KEYS[1], ARGV[2]); " +
"return 0; " +
"else " +
"redis.call('del', KEYS[1]); " +
"redis.call('publish', KEYS[2], ARGV[1]); " +
"return 1; " +
"end; " +
"return nil;",
Arrays.asList(getRawName(), getChannelName()), LockPubSub.UNLOCK_MESSAGE, internalLockLeaseTime, getLockName(threadId));
}
可以看到,其實又是一段lua腳本,繼續復制出來分析一下。
-- KEYS[1] 加鎖的對象(也就是我們傳入的的鎖名稱)
-- KEYS[2] 監聽該鎖的頻道 也就是publish要發送鎖被釋放的頻道,用于在鎖釋放時通知其他客戶端可以重新獲取鎖了
-- ARGV[1]:解鎖消息
-- ARGV[2] 表示鎖的過期時間
-- ARGV[3]:UUID+當前線程id
-- 先判斷自己的鎖是不是已經釋放了 ==0 表示key不存在了,也就是鎖被釋放了
if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then
-- 返回nil,也就是null, 表示釋放鎖成功
return nil;
end ;
-- 對鎖的重入次數減一 因為重入一次counter會+1,所以釋放時每次也只能-1,跟重入次數匹配
local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1);
-- 如果重入次數仍然大于0,續約過期時間
if (counter > 0) then
redis.call('pexpire', KEYS[1], ARGV[2]);
-- 返回解說失敗
return 0;
else
-- 表示重入次數已經為0了,刪除鎖的key
redis.call('del', KEYS[1]);
-- 使用publish發布一個消息,其他訂閱了的客戶端收到消息,就說明解鎖成功了餓、然后可以重新獲取鎖了
redis.call('publish', KEYS[2], ARGV[1]);
-- 返回1 表示解鎖成功
return 1;
end ;
return nil;
其實就是在解鎖的時候,已經解鎖了直接返回成功,可重入次數沒有到0,將會解鎖失敗,直到可重入次數重新減到0后,開始刪除鎖的key.
并且此時會使用publish發送一個消息在渠道上,訂閱者們訂閱到了,就說明鎖已經被釋放了,然后可以從重新獲取鎖了。
3、小結
Redisson實現分布式鎖,就是使用lua腳本保證原子性和互斥性的。每次都判斷是不是自己持有鎖,才進行操作,這就保證了同一性。
在加鎖時使用incrby對key對應的value值進行自增,減鎖時自減實現鎖的可重入性。
使用redis的超時自動過期來保證鎖的容錯性,不會一直鎖死下去。所以鎖的最大續約時間是防止思索的一個有效的方法。