org.apache.curator:master選舉和分佈式鎖

1. master選舉(LeaderSelector)

1)LeaderSelector構造函數

 在leaderPath上創建分佈式鎖:mutex = new InterProcessMutex(client, leaderPath)分佈式

2)LeaderSelector.start

當前WorkServer參與master選舉函數

若autoRequeue爲ture,則當前WorkServer在未能獲取leadership || 獲取並釋放leadership時,將自動進入下一輪master選舉oop

3)LeaderSelector.doWorkLoop -> takeLeadership

捕獲InterruptedException並進行自我中斷,若autoRequeue爲ture,則忽略一切捕獲的異常ui

獲取分佈式鎖 -> 獲取leadership ->釋放分佈式鎖,獲取分佈式鎖失敗時將等待spa

2. 分佈式鎖(InterProcessMutex)

1)InterProcessMutex和LockInternals構造函數

maxLeases默認爲1:只選舉一個master線程

driver默認爲StandardInternalsDriver類型3d

2)獲取分佈式鎖

InterProcessMutex.acquire

LockInternals.attemptLock

StandardLockInternalsDriver.createsTheLock

在zookeeper上創建臨時順序(-e -s)節點,獲取該節點在zookeeper上的完整路徑(ourPath)blog

LockInternals.internalLockLoop

(1)basePath下的子節點依字符串天然順序排序:getSortedChildren排序

(2)driver.getsTheLock(client, children, sequenceNodeName, maxLeases),其中sequenceNodeName爲createsTheLock所建立的臨時順序節點的名稱,如lock-0000000001ip

  若sequenceNodeName爲children中的首個元素,則說明當前WorkServer爲首個成功建立臨時順序節點的WorkServer,當前WorkServer成功獲取分佈式鎖(haveLock = true)

  不然,建立watcher監聽前置節點的變化 -> 當前WorkServer等待:client.getData().usingWatcher(watcher).forPath(previousSequencePath) -> wait

StandardLockInternalsDriver.getsTheLock

maxLeases爲1

sequenceNodeName在children中的位置 < 1:getsTheLock = true,pathToWatch = null

sequenceNodeName在children中的位置 >= 1:getsTheLock = false,pathToWatch = sequenceNodeName前置節點

3)釋放分佈式鎖

InterProcessMutex.release

LockInternals.releaseLock

刪除當前WorkServer在zookeeper上建立的臨時順序節點:將觸發全部WorkServer中設置LockInternals.watcher

LockInternals.watcher

watcher在LockInternals.internalLockLoop中被設置

喚醒當前WorkServer:每一個WorServer表明一個JVM線程,多個WorkServer可能位於不一樣JVM上,也可能位於不一樣主機上

相關文章
相關標籤/搜索