ZkClient 是一个开源软件,也托管在 github。它封装了 zookeeper 原生 API。java
先须要在 javaws 网站上下载 ZKClient 的 jar 包。git
import java.util.List; import com.github.zkclient.IZkChildListener; import com.github.zkclient.ZkClient; public class Get_Children_Sample { public static void main(String[] args) throws Exception { String path = "/zookeeper-ch5"; ZkClient zkClient = new ZkClient("202.201.*.*:2100", 5000); zkClient.subscribeChildChanges(path, new IZkChildListener(){ public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception{ System.out.println(parentPath + " 's child changed, currentChilds:" + currentChilds); } }); zkClient.createPersistent(path); Thread.sleep( 1000 ); System.out.println(zkClient.getChildren(path)); zkClient.createPersistent(path+"/c1"); Thread.sleep( 1000 ); zkClient.delete(path+"/c1"); Thread.sleep( 1000 ); zkClient.delete(path); Thread.sleep( Integer.MAX_VALUE); } }
注意 ZkClient
中的 IP 地址应该和 /opt/zookeeper-3.4.6/conf/zoo.cfg
中配置的 IP 地址一致,且在 /opt/zookeeper-3.4.6/bin
目录下启动 zookeepergithub
./zkServer.sh start
服务器
调用 ZkClient create API
增长节点。网站
调用 ZkClient delete API
删除节点。code
客户端经过注册相关的事件监听来实现对 ZooKeeper 服务端事件的订阅。使用以下API来进行监听:htm
List<String> subscribeChildChange(String path, IZkChildListener listener)
接口
订阅的事件由 Listener 接口来处理:事件
public interface IZkChildListener(){ public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception; }
打印结果get
/zookeeper-ch5 's child changed, currentChilds:[] [] /zookeeper-ch5 's child changed, currentChilds:[c1] /zookeeper-ch5 's child changed, currentChilds:[] /zookeeper-ch5 's child changed, currentChilds:null
调用 createPersistent(path)
会建立父节点 [],客户端收到来自服务器的事件通知,打印 /zookeeper-ch5 's child changed, currentChilds:[]
。
而后添加 /c1
子节点,客户端收到事件通知,打印。