文章目录
zkClient.subscribeChildChanges() 监听当前节点和下面子节点的新增、删除
监听当前节点和下面子节点的新增、删除。不监听数据发生修改和变化。
参数说明:
- 第1个参数: 路径path,要监听的节点
- 第2个参数:这个一个回调函数,要实现 IZkChildListener 接口,并重写 subscribeChildChanges()
package com.aop8.zkclient.watcher;
public class ZkClientWatcher1 {
/** session超时时间 */
static final int SESSION_OUTTIME = 5000;//ms
public static void main(String[] args) throws Exception {
ZkClient zkc = new ZkClient(new ZkConnection(CommonsUtils.CONNECT_ADDR), 5000);
//对父节点添加监听子节点变化。
zkc.subscribeChildChanges("/super", new IZkChildListener() {
@Override
public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
System.out.println("parentPath: " + parentPath);
System.out.println("currentChilds: " + currentChilds);
}
});
Thread.sleep(3000);
zkc.createPersistent("/super");
Thread.sleep(1000);
zkc.createPersistent("/super" + "/" + "c1", "c1内容");
Thread.sleep(1000);
zkc.createPersistent("/super" + "/" + "c2", "c2内容");
Thread.sleep(1000);
zkc.delete("/super/c2");
Thread.sleep(1000);
zkc.deleteRecursive("/super");
Thread.sleep(Integer.MAX_VALUE);
}
}
zkClient.subscribeDataChanges() 监听 当前节点和子节点的内容修改、删除
这是一个回调函数,要实现 IZkDataListener 接口,并重写 handleDataChange() 和 handleDataDeleted() 两个方法。
package com.aop8.zkclient.watcher;
public class ZkClientWatcher2 {
/** session超时时间 */
static final int SESSION_OUTTIME = 5000;//ms
public static void main(String[] args) throws Exception {
ZkClient zkc = new ZkClient(new ZkConnection(CommonsUtils.CONNECT_ADDR), 5000);
zkc.createPersistent("/super", "1234");
//对父节点添加监听子节点变化。
zkc.subscribeDataChanges("/super", new IZkDataListener() {
@Override
public void handleDataChange(String path, Object data) throws Exception {
System.out.println("变更的节点为:" + path + ", 变更内容为:" + data);
}
@Override
public void handleDataDeleted(String path) throws Exception {
System.out.println("删除的节点为:" + path);
}
});
Thread.sleep(3000);
zkc.writeData("/super", "456", -1);
Thread.sleep(1000);
zkc.delete("/super");
Thread.sleep(Integer.MAX_VALUE);
zkc.close();
}
}