码迷,mamicode.com
首页 > 系统相关 > 详细

二十、curator recipes之NodeCache

时间:2019-01-17 01:17:08      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:code   api   apach   print   false   ref   ram   demo   targe   

简介 

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();
    }
}

 

二十、curator recipes之NodeCache

标签:code   api   apach   print   false   ref   ram   demo   targe   

原文地址:https://www.cnblogs.com/lay2017/p/10280238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!