初始化对象连接到zookeeper服务:
public ZooKeeper initZk(){
final CountDownLatch countDownLatch = new CountDownLatch(1);
ZooKeeper zk = null;
try {
zk = new ZooKeeper("127.0.0.1:2181", 3000, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
countDownLatch.countDown();
}
System.out.println("Watch =>" + watchedEvent.getType());
}
});
countDownLatch.await();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return zk;
}
一旦连接成功,将建立一个session,并为该客户端分配一个ID,获得zk对象之后我们就可以通过这个对象进行对zookeeper服务进行操作:
新增节点:
create(java.lang.String path, byte[] data, java.util.List<ACL> acl, CreateMode createMode)
创建一个觉有指定path的节点;
create(java.lang.String path, byte[] data, java.util.List<ACL> acl, CreateMode createMode,AsyncCallback.StringCallback cb, java.lang.Object ctx)
创建一个异步并具有指定path的节点;
参数: