1. 程式人生 > >八、curator recipes之選舉主節點LeaderSelector

八、curator recipes之選舉主節點LeaderSelector

javadoc get state try cto import throw lose 進行

簡介

前面我們看到LeaderLatch對於選舉的實現:https://www.cnblogs.com/lay2017/p/10264300.html

節點在加入選舉以後,除非程序結束或者close()退出選舉,否則加點自加入選舉以後將持續持有或者保持對主節點的競爭。

recipes的另外一個實現Leader Election則不同,被選為主節點的節點任務如果執行完就會放棄主節點,然後由剩下的節點進行主節點競爭。如果你希望已經執行完的主節點再次加入主節點選舉那麽你需要調用autoRequeue()方法去自動加入。

官方文檔:http://curator.apache.org/curator-recipes/leader-election.html

javaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/leader/LeaderSelector.html

代碼示例

以下代碼你可以通過是否調用autoRequeue來看看console的輸出有什麽不同

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.ExponentialBackoffRetry; public class LeaderElectionDemo { private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new
ExponentialBackoffRetry(3000, 3)); private static String path = "/mutex/path/0001"; static { client.start(); } public static void main(String[] args) throws InterruptedException { startThread0(); Thread.sleep(10); startThread1(); Thread.sleep(50000); client.close(); } public static void startThread0() { new Thread(() -> { LeaderSelector selector = new LeaderSelector(client, path, new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework curatorFramework) throws Exception { System.out.println("thread0 is leader"); } @Override public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) { System.out.println("thread0 state changed,state is " + connectionState.isConnected()); } }); selector.autoRequeue(); selector.start(); }).start(); } public static void startThread1() { new Thread(() -> { LeaderSelector selector = new LeaderSelector(client, path, new LeaderSelectorListener() { @Override public void takeLeadership(CuratorFramework curatorFramework) throws Exception { System.out.println("thread1 is leader"); } @Override public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) { System.out.println("thread1 state changed,state is " + connectionState.isConnected()); } }); selector.autoRequeue(); selector.start(); }).start(); } }

八、curator recipes之選舉主節點LeaderSelector