網站首頁 編程語言 正文
分布式鎖使用
對于 redisson 分布式鎖的使用很簡單:
1、調用 getLock 函數獲取鎖操作對象;
2、調用 tryLock 函數進行加鎖;
3、調用 unlock 函數進行解鎖;
注意 unlock 操作需要放到 finally 代碼段中,保證鎖可以被釋放。
private void sumLock() {
lock = redissonClient.getLock("sum-lock");
boolean b = lock.tryLock();
if (!b) {
log.info("獲取不到鎖");
return;
}
try {
for (int j = 0; j < 20000; j++) {
++sum;
}
} finally {
lock.unlock();
}
}
getLock
getLock 實例化 RedissonLock,相當于 Lock lock = new ReentrantLock() 操作;
public RLock getLock(String name) {
? ? // 實例化 RedissonLock,參數為指令執行器和鎖名稱
? ? return new RedissonLock(this.connectionManager.getCommandExecutor(), name);
}
public RedissonLock(CommandAsyncExecutor commandExecutor, String name) {
? ? super(commandExecutor, name);
? ? // 命令執行器,用于執行lua腳本
? ? this.commandExecutor = commandExecutor;
? ? // 連接管理器的ID
? ? this.id = commandExecutor.getConnectionManager().getId();
? ? // 鎖續期時間(看門狗),鎖默認續期時間是 30s。
? ? this.internalLockLeaseTime = commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout();
? ? this.entryName = this.id + ":" + name;
? ? this.pubSub = commandExecutor.getConnectionManager().getSubscribeService().getLockPubSub();
}
tryLock
@Override
public boolean tryLock() {
? ? return get(tryLockAsync());
}
@Override
public RFuture<Boolean> tryLockAsync() {
? ? return tryLockAsync(Thread.currentThread().getId());
}
@Override
public RFuture<Boolean> tryLockAsync(long threadId) {
? ? return tryAcquireOnceAsync(-1, -1, null, threadId);
}
這里是一系列的調用,可以直接跳過,直接進入到 tryAcquireOnceAsync 函數,看看 tryAcquireOnceAsync 函數的處理邏輯。
private RFuture<Boolean> tryAcquireOnceAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId) {
? ? // 由于我們調用tryLocak沒有傳遞任何參數,leaseTime默認為-1,不走判斷
? ? if (leaseTime != -1) {
? ? ? ? return tryLockInnerAsync(waitTime, leaseTime, unit, threadId, RedisCommands.EVAL_NULL_BOOLEAN);
? ? }
? ??
? ? // 調用獲取鎖 枷鎖的主要邏輯在這里
? ? RFuture<Boolean> ttlRemainingFuture = tryLockInnerAsync(waitTime,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_NULL_BOOLEAN);
? ??
? ? ttlRemainingFuture.onComplete((ttlRemaining, e) -> {
? ? ? ? // 如果發生異常那么直接放回了
? ? ? ? if (e != null) {
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? // 鎖續期
? ? ? ? if (ttlRemaining) {
? ? ? ? ? ? scheduleExpirationRenewal(threadId);
? ? ? ? }
? ? });
? ? // 返回結果
? ? return ttlRemainingFuture;
}
<T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
// 將時間轉化為毫秒
internalLockLeaseTime = unit.toMillis(leaseTime);
// 執行腳本
return evalWriteAsync(getName(), 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(getName()), internalLockLeaseTime, getLockName(threadId));
}
Redisson 中存儲鎖的數據類型結構采用的的是 hash,Key 為鎖名稱,VALUE的屬性是 Redisson 客戶端ID和線程ID組合而成的字符串,值是鎖的重入次數,采用 hash 計數實現鎖的重入性。
該函數主要執行 lua 腳本,腳本的邏輯為:
1、redis.call(‘exists’, KEYS[1]) == 0 用于判斷鎖是否存在,等于 0 說明不存在,表明此時沒有客戶端持有鎖,此客戶端獲取鎖成功;走步驟 2,否則走步驟 4;
2、設置鎖,并且對鎖進行 +1 操作,標識獲取鎖的次數;
3、為鎖設置過期時間,成功返回 nil;
4、redis.call(‘hexists’, KEYS[1], ARGV[2]) == 1 判斷鎖是否本客戶端持有,等于1說明是,此時是再次獲取鎖(重入),走步驟 5,否則走 7;
5、對鎖進行 +1 操作,標識獲取鎖的次數;
6、為鎖設置過期時間,成功返回 nil;
7、如果1和4的判斷都不滿足,那么返回鎖的的剩余時間;
unLock
@Override
public void unlock() {
? ? try {
? ? ? ? get(unlockAsync(Thread.currentThread().getId()));
? ? } catch (RedisException e) {
? ? ? ? if (e.getCause() instanceof IllegalMonitorStateException) {
? ? ? ? ? ? throw (IllegalMonitorStateException) e.getCause();
? ? ? ? } else {
? ? ? ? ? ? throw e;
? ? ? ? }
? ? }
}
@Override
public RFuture<Void> unlockAsync(long threadId) {
? ? RPromise<Void> result = new RedissonPromise<Void>();
? ? // 釋放鎖的邏輯主要這里
? ? RFuture<Boolean> future = unlockInnerAsync(threadId);
? ? future.onComplete((opStatus, e) -> {
? ? ? ? cancelExpirationRenewal(threadId);
? ? ? ? if (e != null) {
? ? ? ? ? ? result.tryFailure(e);
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? if (opStatus == null) {
? ? ? ? ? ? IllegalMonitorStateException cause = new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: "
? ? ? ? ? ? ? ? ? ? + id + " thread-id: " + threadId);
? ? ? ? ? ? result.tryFailure(cause);
? ? ? ? ? ? return;
? ? ? ? }
? ? ? ? result.trySuccess(null);
? ? });
? ? return result;
}
這里是一系列的調用,可以直接跳過,直接進入到 unlockInnerAsync 函數,看看 unlockInnerAsync 函數的處理邏輯。
protected RFuture<Boolean> unlockInnerAsync(long threadId) {
return evalWriteAsync(getName(), 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(getName(), getChannelName()), LockPubSub.UNLOCK_MESSAGE, internalLockLeaseTime, getLockName(threadId));
}
該函數主要執行 lua 腳本,腳本的邏輯為:
1、redis.call(‘hexists’, KEYS[1], ARGV[3]) == 0 用于判斷鎖是否為當前客戶端持有,等于 0 說明不是直接返回 nil,否則說明是,走步驟 2;
2、對鎖進行 -1 操作,并且獲取其計數 counter;
3、判斷 counter > 0,如果大于 0 說明該客戶端多次獲取鎖,對鎖進行續期并且返回 0,因為此時業務還沒有執行完畢,否則走步驟 4;
4、如果count 小于等于 0 則刪除鎖,發送釋放鎖的消息,返回 1;
5、如果以上邏輯都不滿足,那么直接返回nil;
總結
redisson 加鎖解鎖:
1、redisson 使用 lua 腳本保證命令執行的原子性;
2、redisson 使用 redis 的 hash 數據結構類型來存儲鎖信息,使用 鎖名稱作為 hash 名稱,使用“客戶端ID:線程ID”作為鍵,使用重入次數作為值;
3、每次獲取鎖,會對值進行 +1 操作,并且設置過期時間;
4、每次釋放鎖,會對值進行 -1 操作,如果沒有減少為 0,則繼續設置鎖的超時時間,否則刪除鎖,并且發送釋放鎖的消息。
原文鏈接:https://blog.csdn.net/skystep/article/details/125460871
相關推薦
- 2022-10-27 Windows?Server?2019?安裝后的一些設置收集_win服務器
- 2023-04-27 React中state屬性和生命周期的使用_React
- 2022-04-24 redis用list做消息隊列的實現示例_Redis
- 2022-11-04 C++多態特性之派生與虛函數與模板詳細介紹_C 語言
- 2023-07-22 macos設置環境變量path詳解
- 2022-02-23 MAC清除所有的mobileprovision
- 2022-04-30 DataGridView實現點擊列頭升序和降序排序_C#教程
- 2023-04-20 文本超出顯示省略號在項目中的使用
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支