参考:从Paxos到Zookeeper分布式一致性原理和实践
使用的zk依赖是cdh5.16.2的3.4.5
1 2 3 4 5 6 7
| <!-- zookeeper --> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.5-cdh5.16.2</version> </dependency>
|
代码,其中CountDownLatch计数器参考:Java多线程——其他工具类CyclicBarrier、CountDownLatch和Exchange
初始化的计数器为1,当zk client连接到zk集群后,zk集群返回的状态为connected,计数器-1,触发InterruptedException
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| package com.bigdata.zookeeper;
import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.CountDownLatch;
public class ZkExample implements Watcher {
public static CountDownLatch connectedSemaphore = new CountDownLatch(1);
public static void main(String[] args) throws Exception { ZooKeeper zk = new ZooKeeper("master:2181", 5000, new ZkExample()); System.out.println(zk.getState()); try { connectedSemaphore.await(); } catch (InterruptedException e) { System.out.println("Zk session established"); } }
@Override public void process(WatchedEvent watchedEvent) { System.out.println(watchedEvent); if (Event.KeeperState.SyncConnected == watchedEvent.getState()) { connectedSemaphore.countDown(); } } }
|
输出