1.Curator Cache 与原生ZooKeeper Wacher区别

原生的ZooKeeper Wacher是一次性的:一个Wacher一旦触发就会被移出,如果你想要反复使用Wacher,就要在Wacher被移除后重新注册,使用起来很麻烦。使用Curator Cache 可以反复使用Wacher了。

2.Curator Cache 和Curator Wacher区别

2.相关类

Curator Cache主要提供了一下三组类,分别用于实现对节点的监听,子节点的监听和二者的混合:

1.NodeCache,NodeCacheListener,ChildData,节点创建,节点数据内容变更,不能监听节点删除。

2.PathChildrenCache,PathChildrenCacheListener,PathChildrenCacheEvent监听指定节点的子节点的变更包括添加,删除,子节点数据数据变更这三类。

3.TreeCache,TreeCacheListener,TreeCacheEvent,TreeCacheSelector

3.节点监听

package cn.francis.maven.hello.ZooKeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.CloseableUtils;
import org.apache.zookeeper.CreateMode; public class NodeCacheDemo {
public static void main(String[]args) throws Exception{
TestingServer server=null;
CuratorFramework client=null;
NodeCache nodeCache=null;
String path="/francis/nodecache/a"; try{
server=new TestingServer();
client= CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000,3));
client.start(); path=client.create().creatingParentsIfNeeded().withProtection().withMode(CreateMode.EPHEMERAL).forPath(path,"init".getBytes()); nodeCache=new NodeCache(client,path,false);
nodeCache.start();
addListener(nodeCache); client.setData().forPath(path,"hello".getBytes());
Thread.sleep(1000);
client.delete().deletingChildrenIfNeeded().forPath(path);
Thread.sleep(Integer.MAX_VALUE); }catch(Exception e){
e.printStackTrace();
}finally{ //这里因为是测试,没有加他们。
//CloseableUtils.closeQuietly(nodeCache);
/// CloseableUtils.closeQuietly(client);
// CloseableUtils.closeQuietly(server);
}
} public static void addListener(NodeCache nodeCache){
//监听类型:节点是否存在,节点数据内容改变,不监听节点删除。
nodeCache.getListenable().addListener(new NodeCacheListener(){ @Override
public void nodeChanged() throws Exception {
// TODO Auto-generated method stub
if(nodeCache.getCurrentData()!=null)
System.out.println("path:"+nodeCache.getCurrentData().getPath()+",data:"+new String(nodeCache.getCurrentData().getData())); }});
}
}

在上面的代码中首先创建了一个节点,然后创建用这个节点路径来创建NodeCache,启动NodeCache,添加NodeCacheListener。然后调用setData来修改节点数据。上面的代码输入如下:

path:/francis/nodecache/_c_d5be73ca-592c-4eda-b7c4-c8ec60ef39a8-a,data:hello

子节点监听:

PathChildrenCache的构造函数如下:

public PathChildrenCache(CuratorFramework client,
String path,
boolean cacheData)
Parameters:
client - the client
path - path to watch
cacheData - if true, node contents are cached in addition to the stat

其中最主要的是cacheData,如果为true,那么当对子节点调用setData时,PathChildrenCache会受到这个CHILD_UPDATED事件。

下面看一下demo:

package cn.francis.maven.hello.ZooKeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent.Type;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.utils.ZKPaths;
import org.apache.hadoop.mapred.join.Parser.TType;
import org.apache.zookeeper.CreateMode; public class NodeCacheDemo {
public static void main(String[]args) throws Exception{
TestingServer server=null;
CuratorFramework client=null;
NodeCache nodeCache=null;
String path="/francis/nodecache/b"; try{
server=new TestingServer();
client= CuratorFrameworkFactory.newClient(server.getConnectString(),new ExponentialBackoffRetry(1000,3));
client.start(); //这里将第三个参数cacheData设置为true,这样当对子节点调用setData时,会受到CHILDREN_UPDATE通知。
PathChildrenCache childrenCache=new PathChildrenCache(client,path,true);


childrenCache.start(StartMode.POST_INITIALIZED_EVENT); childrenCache.getListenable().addListener(new PathChildrenCacheListener(){ @Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
// TODO Auto-generated method stub
if(event.getType()==Type.INITIALIZED){
System.out.println("create"+event.getData().getPath());
}else if(event.getType()==Type.CHILD_ADDED){
System.out.println("create"+event.getData().getPath());
}else if(event.getType()==Type.CHILD_REMOVED){
System.out.println("remove:"+event.getData().getPath());
}else if(event.getType()==Type.CHILD_UPDATED){
//System.out.println("update:"+event.getData().getPath());
System.out.println("update:"+new String(event.getData().getData()));
} }}); //创建父节点
System.out.println(client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path,"init".getBytes()));
Thread.sleep(1000); //创建子节点
String childPath1=ZKPaths.makePath(path, "a");
childPath1=client.create().withMode(CreateMode.PERSISTENT).forPath(childPath1,"1".getBytes());
Thread.sleep(1000); //对子节点赋值
client.setData().forPath(childPath1,"aaa".getBytes());
Thread.sleep(1000); //删除子节点
client.delete().forPath(childPath1);
client.delete().deletingChildrenIfNeeded().forPath("/francis"); Thread.sleep(2000); }catch(Exception e){
e.printStackTrace();
}finally{
CloseableUtils.closeQuietly(nodeCache);
CloseableUtils.closeQuietly(client);
CloseableUtils.closeQuietly(server);
}
}

3.TreeNodeCache

TreeNodeCache将NodeCache和PathChildrenCache功能结合到一起了。他不仅可以对子节点和父节点同时进行监听。如下:

package cn.francis.maven.hello.ZooKeeper;

import java.util.Map;

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.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
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.framework.recipes.cache.PathChildrenCacheEvent.Type;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.utils.ZKPaths;
import org.apache.hadoop.mapred.join.Parser.TType;
import org.apache.zookeeper.CreateMode; public class NodeCacheDemo {
public static void main(String[]args) throws Exception{
TestingServer server=null;
CuratorFramework client=null;
NodeCache nodeCache=null;
String path="/francis/nodecache/b"; try{
server=new TestingServer();
client= CuratorFrameworkFactory.newClient(server.getConnectString(),new ExponentialBackoffRetry(1000,3));
client.start(); TreeCache treeNodeCache=new TreeCache(client,path); treeNodeCache.start(); treeNodeCache.getListenable().addListener(new TreeCacheListener(){ @Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
// TODO Auto-generated method stub
switch(event.getType()){
case NODE_ADDED:
System.out.println("added:"+event.getData().getPath());
break;
case NODE_UPDATED:
System.out.println("updated:"+event.getData().getPath());
break;
case NODE_REMOVED:
System.out.println("removed:"+event.getData().getPath());
break;
default:
System.out.println("other:"+event.getType());
}
} }); //创建父节点
client.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(path,"init".getBytes());
Thread.sleep(1000); //创建子节点
String childPath1=ZKPaths.makePath(path, "a");
childPath1=client.create().withMode(CreateMode.PERSISTENT).forPath(childPath1,"1".getBytes());
Thread.sleep(1000); //对子节点赋值
client.setData().forPath(childPath1,"aaa".getBytes());
Thread.sleep(1000); //对子节点赋值
client.setData().forPath(path,"aaa".getBytes());
Thread.sleep(1000); //删除子节点
client.delete().forPath(childPath1);
client.delete().deletingChildrenIfNeeded().forPath("/francis"); Thread.sleep(2000); }catch(Exception e){
e.printStackTrace();
}finally{ //这里因为是测试,没有加他们。
CloseableUtils.closeQuietly(nodeCache);
CloseableUtils.closeQuietly(client);
CloseableUtils.closeQuietly(server);
}
}
}

输出如下:

other:INITIALIZED
added:/francis/nodecache/b
added:/francis/nodecache/b/a
updated:/francis/nodecache/b/a
updated:/francis/nodecache/b
removed:/francis/nodecache/b/a
removed:/francis/nodecache/b

Curator Cache的更多相关文章

  1. zk 09之:Curator之二:Path Cache监控zookeeper的node和path的状态

    在实际应用开发中,当某个ZNode发生变化后我们需要得到通知并做一些后续处理,Curator Recipes提供了Path Cache 来帮助我们轻松实现watch ZNode. Path Cache ...

  2. Curator Recipes(Cache&Counter)

    Cache 路径缓存(Path Cache) 监视一个ZNode,当子节点增加.更新.删除改变状态时,路径缓存会在本地保存当前子节点及其数据和状态. public PathChildrenCache( ...

  3. Curator框架的使用

    Curator框架的目的是减少用户的复杂度,毕竟原生的Zookeeper难以使用. 这里举一个使用例子. 第一步:建立连接 // 以下代码与192.168.1.101:2181建立了连接Curator ...

  4. Apache Curator: Zookeeper客户端

    Apache Curator Framework url: http://curator.apache.org/curator-framework/ The Curator Framework is ...

  5. Zookeeper开源客户端框架Curator简介

    Curator是Netflix开源的一套ZooKeeper客户端框架. Netflix在使用ZooKeeper的过程中发现ZooKeeper自带的客户端太底层, 应用方在使用的时候需要自己处理很多事情 ...

  6. (原) 2.3 Curator使用

    本文为原创文章,转载请注明出处,谢谢 Curator使用 1.jar包引入,演示版本为2.6.0,非maven项目,可以下载jar包导入到项目中 <dependency> <grou ...

  7. Zookeeper开源客户端框架Curator简介[转]

    Curator是Netflix开源的一套ZooKeeper客户端框架. Netflix在使用ZooKeeper的过程中发现ZooKeeper自带的客户端太底层, 应用方在使用的时候需要自己处理很多事情 ...

  8. ZooKeeper(3.4.5) 使用Curator监听事件

    转载:http://www.mamicode.com/info-detail-494364.html 标签: ZooKeeper原生的API支持通过注册Watcher来进行事件监听,但是Watcher ...

  9. 通过Curator操作Zookeeper的简单例子代码

    Curator主要解决了三类问题: 一个是ZooKeeper client与ZooKeeper server之间的连接处理; 一个是提供了一套Fluent风格的操作API; 一个是ZooKeeper各 ...

随机推荐

  1. C#微信公众号开发系列教程二(新手接入指南)

    http://www.cnblogs.com/zskbll/p/4093954.html 此系列前面已经更新了两篇博文了,都是微信开发的前期准备工作,现在切入正题,本篇讲解新手接入的步骤与方法,大神可 ...

  2. Nodejs 的 Express框架 学习体会 补充中。。。

    最近为了用Shadow Socket FQ,到https://bandwagonhost.com上买了一个便宜的vps,19.99美元一年.服务器闲着也是闲着,就想搭建一个简单的博客. Express ...

  3. Devils never rest

    一个人 练习一个人 书名 看到就被吸引了,然后亚马逊下手 作者很文艺,我很喜欢作者内心的那份宁静. 我一个人吃饭 旅行 到处走走停停 也一个人看书 写信 自己对话谈心 依然是心内一片寂静,总是不由自主 ...

  4. node09-cookie

    目录:node01-创建服务器 node02-util node03-events node04-buffer node05-fs node06-path node07-http node08-exp ...

  5. 结合实例详细介绍encodeURI()、encodeURIComponent()、decodeURI()、decodeURIComponent()使用方法

    在介绍encodeURI().encodeURIComponent().decodeURI().decodeURIComponent()方法前我们需要了解Global对象的概念:   Global(全 ...

  6. Cocos2dx

    初玩Cocos2dx,多多包涵. 感觉版本之间的差异比较大,相对前面的版本来说,3.X更容易上手,更方便了. 一.安装python.我的python-2.7.3.配置环境变量 系统变量里:在Path里 ...

  7. MVC 添加Area

    在MVC项目中经常会使用到Area来分开不同的模块让项目结构更加的清晰. 步骤如下: 项目 –> 添加 -> 区域 ( Area ) 输入 Admin 添加成功后 Area包含: 创建一个 ...

  8. js如何求一组数中的极值

    这是一个很简单的问题,现在我们从循环开始,例如一组数[5,2,1,3,4];求其中的最大值,那么首先我们要定义一个max的中间变量,遍历数组,当遇到比max值大则赋值给max,直到循环结束,就能获取这 ...

  9. C++ 字符处理函数

    C/C++里有一个头文件#include <ctype.h>,里面定义了很多字符函数,在实际开发中,用起来很方面. int isalpha(int ch)  若ch是字母('A'-'Z', ...

  10. kettle系列-我的开源kettle管理平台[kettle-manager]介绍

    kettle管理工具 专门为kettle这款优秀的ETL工具开发的web端管理工具. 项目简介 kettle作为非常优秀的开源ETL工具得到了非常广泛的使用,一般的使用的都是使用客户端操作管理,但问题 ...