1.ZkClient zkc =new ZKClient(new zkConnection(CONNECT_ADDR),10000);
(1)create and delete方法
zkc.createEphemeral("/temp"); //创建临时节点
zkc.createPersistent("/super/c1",true); //创建持久化节点
zkc.deleteRecursive("/super");
(2) 设置path和data 并且读取子节点和每个节点的内容
zkc.createPersistent("/super","1234");
zkc.createPersistent("/super/c1","c1内容");
zkc.createPersistent("/super/c2","c2内容");
List<String> list =zkc.getChildrent("/super");
for(String p : list){
System.out.println(p);
String rp ="/super/" +p;
String data =zkc.readData(rp);
System.out.println("节点为:"+rp+",内容为: "+data);
}
(3) 更新和判断节点是否存在
zkc.writeData("/super/c1","新内容");
System.out.println(zkc.readData("/super/c1"));
System.out.println(zkc.exists("/super/c1"));
(4)递归删除/super内容
zkc.deleteRecursive("/super");
zkc.close();
2.ZkClient的监听
//对父节点添加监听子节点变化(只监听节点的新增、删除,不监听节点内容的更新)
zkc.subscribeChildChanges("/super",new IZkChildListenter(){
@Override
public void handleChildChange(String parentPath,List<String> currentChilds) throws Exception{
System.out.println("parentPath"+parentPath);
System.out.println("currentChilds:"+currentChilds);
}
});
//对父节点添加监听子节点变化
zkc.subscribeDataChanges("/super",new IZkDataListenter(){
@Override
public void handleDataDeleted(String path) throws Exception{
System.out.println("删除的节点为:"+path);
}
@Override
public void handleDataChange(String path,Object data) throw Exception {
System.out.println("变更的节点为:"+path +",变更的内容为:"+data);
}
});