标签:
package leader; import java.util.List; import java.util.concurrent.TimeUnit; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; /** * 模拟leader选举 * * 1、zookeeper服务器上有一个/leader节点 * 2、在/leader节点下创建短暂顺序节点/leader/lock-xxxxxxx * 3、获取/leader的所有子节点并注册监听 * 4、拿自己的顺序号跟其他子节点的顺序号比较,如果自己的是最小的则获得leader * 5、监听到/leader子节点发生变化则执行步骤3、 4尝试获取leader * */ public class Client { public static final String HOSTS = "hadoop1:2181"; public static final String LEADER_PATH = "/leader"; private String path = null; public void run() throws Exception { ZooKeeper zk = ZKUtils.open(HOSTS); path = zk.create(LEADER_PATH + "/lock-", null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); getLeader(zk); TimeUnit.DAYS.sleep(1); } private void getLeader(final ZooKeeper zk) throws KeeperException, InterruptedException { //获取/leader下的所有子节点 //注册/leader子节点观察 List<String> children = zk.getChildren(LEADER_PATH, new Watcher() { @Override public void process(WatchedEvent event) { //如果/leader子节点发生变化,则再进行一次getLeader if(event.getType().equals(EventType.NodeChildrenChanged)) { try { getLeader(zk); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } }); //拿自己的顺序号跟/leader所有子节点的顺序号比较,如果是最小的则拿到leader long seq = getSeq(path); boolean isMin = true; for (String child : children) { long childSeq = getSeq(child); if(childSeq < seq) { isMin = false; break; } } if(isMin) { System.out.printf("我拿到锁了, path: %s, thread: %s", path, Thread.currentThread().getName() ); } } public long getSeq(String path) { return Long.parseLong(path.split("-")[1]); } }
Test .java
package leader; public class Test { //多次执行这个类,模拟多个客户端竞选leader public static void main(String[] args) throws Exception { new Client().run(); } }
其实在上面的实现中存在几个问题:
标签:
原文地址:http://www.cnblogs.com/lishouguang/p/4558986.html