選舉使用zk節(jié)點(diǎn)jobName/leader/election/latch
募判,通過(guò)使用curator框架完成主節(jié)點(diǎn)的選舉荡含。選舉成功的節(jié)點(diǎn)(實(shí)例)會(huì)創(chuàng)建zk節(jié)點(diǎn)jobName/leader/election/instance
,節(jié)點(diǎn)值為當(dāng)前節(jié)點(diǎn)實(shí)例ID(ip@-@pid)兰伤。
public void electLeader() {
log.debug("Elect a new leader now.");
jobNodeStorage.executeInLeader(LeaderNode.LATCH, new LeaderElectionExecutionCallback());
log.debug("Leader election completed.");
}
通過(guò)上面代碼可知内颗,選舉成功的節(jié)點(diǎn)會(huì)執(zhí)行回調(diào)方法(io.elasticjob.lite.internal.election.LeaderService.LeaderElectionExecutionCallback#execute
):
if (!hasLeader()) {
jobNodeStorage.fillEphemeralJobNode(LeaderNode.INSTANCE, JobRegistry.getInstance().getJobInstance(jobName).getJobInstanceId());
}
任一作業(yè)服務(wù)器啟動(dòng)時(shí),都會(huì)參與主節(jié)點(diǎn)的選舉敦腔。如果選舉成功均澳,則會(huì)寫入分片處理中標(biāo)記,然后執(zhí)行分片符衔。
Leader Latch
In distributed computing, leader election is the process of designating a single process as the organizer of some task distributed among several computers (nodes). Before the task is begun, all network nodes are unaware which node will serve as the "leader," or coordinator, of the task. After a leader election algorithm has been run, however, each node throughout the network recognizes a particular, unique node as the task leader.
LeaderLatches must be started:
leaderLatch.start();
Once started, the LeaderLatch will negotiate with any other LeaderLatch participants that use the same latch path and randomly choose one of them to be the leader. At any time, you can determine if a given instance is the leader by calling:
public boolean hasLeadership()
Return true if leadership is currently held by this instance
Similar to the JDK's CountDownLatch, LeaderLatch has methods that block until leadership is acquired:
public void await()
throws InterruptedException,
EOFException
Causes the current thread to wait until this instance acquires leadership
unless the thread is interrupted or closed.
When you are through with the LeaderLatch instance, you must call close. This removes the instance from the leader election and releases leadership if the instance has it. Once leadership is released, another participating instance (if any) will be chosen as leader.
leaderLatch.close();