Curator实现分布式锁的基本原理-LockInternals.attemptLock
生活随笔
收集整理的這篇文章主要介紹了
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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Curator实现分布式锁的基本原理-I
- 下一篇: Curator实现分布式锁的基本原理-c