日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Curator实现分布式锁的基本原理-LockInternals.attemptLock

發布時間:2024/4/13 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Curator实现分布式锁的基本原理-LockInternals.attemptLock 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
// 嘗試獲取鎖,并返回鎖對應的Zookeeper臨時順序節點的路徑 String attemptLock(long time, TimeUnit unit, byte[] lockNodeBytes) throws Exception{ final long startMillis = System.currentTimeMillis(); // 無限等待時,millisToWait為null final Long millisToWait = (unit != null) ? unit.toMillis(time) : null; // 創建ZNode節點時的數據內容,無關緊要,這里為null,采用默認值(IP地址) final byte[] localLockNodeBytes = (revocable.get() != null) ? new byte[0] : lockNodeBytes; // 當前已經重試次數,與CuratorFramework的重試策略有關 int retryCount = 0; // 在Zookeeper中創建的臨時順序節點的路徑,相當于一把待激活的分布式鎖 // 激活條件:同級目錄子節點,名稱排序最小(排隊,公平鎖),后續繼續分析 String ourPath = null; // 是否已經持有分布式鎖 boolean hasTheLock = false; // 是否已經完成嘗試獲取分布式鎖的操作 boolean isDone = false; while ( !isDone ){ isDone = true; try{ // 從InterProcessMutex的構造函數可知實際driver為StandardLockInternalsDriver的實例 // 在Zookeeper中創建臨時順序節點 ourPath = driver.createsTheLock(client, path, localLockNodeBytes); // 循環等待來激活分布式鎖,實現鎖的公平性,后續繼續分析 hasTheLock = internalLockLoop(startMillis, millisToWait, ourPath); } catch ( KeeperException.NoNodeException e ) {// 容錯處理,不影響主邏輯的理解,可跳過 // 因為會話過期等原因,StandardLockInternalsDriver因為無法找到創建的臨時順序節點而拋出NoNodeException異常 if ( client.getZookeeperClient().getRetryPolicy().allowRetry(retryCount++, System.currentTimeMillis() - startMillis, RetryLoop.getDefaultRetrySleeper()) ){ // 滿足重試策略嘗試重新獲取鎖 isDone = false; } else { // 不滿足重試策略則繼續拋出NoNodeException throw e; } } } if ( hasTheLock ){ // 成功獲得分布式鎖,返回臨時順序節點的路徑,上層將其封裝成鎖信息記錄在映射表,方便鎖重入 return ourPath; } // 獲取分布式鎖失敗,返回null return null; }

?

總結

以上是生活随笔為你收集整理的Curator实现分布式锁的基本原理-LockInternals.attemptLock的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。