二十一、curator recipes之TreeCache

简介

curator的TreeCache允许对某个路径的数据和路径变更以及其下所有子孙节点的数据和路径变更进行监听。

官方文档:http://curator.apache.org/curator-recipes/tree-cache.html

javaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/cache/TreeCache.html

代码示例

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
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;

public class TreeCacheDemo {
    private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 1));
    private static String path = "/treeCache/test/001";
    static {
        client.start();
    }

    public static void main(String[] args) throws Exception {
        if (client.checkExists().forPath(path) == null) {
            client.create().creatingParentsIfNeeded().forPath(path);
        }
        TreeCache cache = new TreeCache(client, path);
        cache.getListenable().addListener((curatorFramework, treeCacheEvent) -> System.out.println(treeCacheEvent.toString()));
        cache.start();
        client.setData().forPath(path, "lay".getBytes());
        client.create().forPath(path + "/child");
        client.setData().forPath(path + "/child", "marry".getBytes());
        client.delete().forPath(path + "/child");
        client.delete().forPath(path);
        Thread.sleep(4000);
        cache.close();
        Thread.sleep(50000);
        client.close();
    }
}

猜你喜欢

转载自www.cnblogs.com/lay2017/p/10280254.html