PathChildrenCache
- NodeCache不仅可以监听节点内容变化,还可以监听指定节点是否存在。如果原本节点不存在,那么Cache就会在节点被创建时触发监听事件,如果该节点被删除,就无法再触发监听事件。
- PathChildrenCache用于监听数据节点子节点的变化情况。
- curator之事件监听详解
API
package com.ruozedata.bigdata.zookeeper;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
public class PathChildrenListener {
private static Logger logger = LoggerFactory.getLogger(PathChildrenListener.class);
private static CountDownLatch watch = new CountDownLatch(1);
private static final String zkServerIps = "ruozedata000:2181";
private static RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
private static CuratorFramework client = CuratorFrameworkFactory.builder()
.connectString(zkServerIps)
.sessionTimeoutMs(15000).retryPolicy(retryPolicy)
.build();
private static void zkWatch(String path) throws Exception {
TreeCache treeCache = new TreeCache(client, path);
treeCache.getListenable().addListener(new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
ChildData eventData = event.getData();
switch (event.getType()) {
case NODE_ADDED:
logger.warn(path + "节点添加" + eventData.getPath() + "\t添加数据为:" + new String(eventData.getData()));
break;
case NODE_UPDATED:
logger.warn(eventData.getPath() + "节点数据更新\t更新数据为:" + new String(eventData.getData()) + "\t版本为:" + eventData.getStat().getVersion());
break;
case NODE_REMOVED:
logger.warn(eventData.getPath() + "节点被删除");
break;
default:
break;
}
}
});
treeCache.start();
watch.await();
}
private static void getZnode(String path) throws Exception {
byte[] bytes = client.getData().forPath(path);
System.out.println(new String(bytes));
}
private static void closeZnode() {
if (client != null) {
client.close();
}
}
public static void main(String[] args) throws Exception {
client.start();
System.out.println(client.getState());
String path = "/ruoze";
getZnode(path);
zkWatch(path);
closeZnode();
}
}