学习 ZooKeeper API 库 Curator(四):路径缓存

路径缓存(Path Cache)菜谱被用于监视 znode,当新增修改删除子节点时,会触发注册的PathChildrenCacheListener 监听器。

示例:

CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1", retryPolicy);  
client.start();  
client.blockUntilConnected();

PathChildrenCache cache = new PathChildrenCache(client, "/test", true);  
cache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);

for(ChildData data: cache.getCurrentData()) {  
    // 处理数据
}

cache.getListenable().addListener(new PathChildrenCacheListener() {  
    public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
        // 处理子节点变更
    }
});