初始化对象连接到zookeeper服务:
1 public ZooKeeper initZk(){ 2 final CountDownLatch countDownLatch = new CountDownLatch(1); 3 ZooKeeper zk = null; 4 try { 5 zk = new ZooKeeper("127.0.0.1:2181", 3000, new Watcher() { 6 @Override 7 public void process(WatchedEvent watchedEvent) { 8 if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { 9 countDownLatch.countDown(); 10 } 11 System.out.println("Watch =>" + watchedEvent.getType()); 12 } 13 }); 14 countDownLatch.await(); 15 } catch (IOException e) { 16 e.printStackTrace(); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 return zk; 21 }
一旦连接成功,将建立一个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的节点;
参数: