简介
Curator的NodeCache允许你监听一个节点,当节点数据更改或者节点被删除的时候将会触发监听。
官方文档:http://curator.apache.org/curator-recipes/node-cache.html
javaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/cache/NodeCache.html
代码示例
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.retry.ExponentialBackoffRetry; public class NodeCacheDemo {
private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 1));
private static String path = "/nodeCache/test/0001";
static {
client.start();
} public static void main(String[] args) throws Exception {
if (client.checkExists().forPath(path) == null) {
System.out.println("not exist");
client.create().creatingParentsIfNeeded().forPath(path);
}
System.out.println("created");
NodeCache nodeCache = new NodeCache(client, path, false);
nodeCache.getListenable().addListener(() -> System.out.println("nodeChanged"));
System.out.println("add listener");
nodeCache.start(true);
System.out.println("cache started");
client.setData().forPath(path, "lay".getBytes());
System.out.println("set data");
client.delete().forPath(path);
System.out.println("deleted");
Thread.sleep(3000);
nodeCache.close();
System.out.println("listener closed");
Thread.sleep(50000);
client.close();
}
}