当前位置: 首页 > 编程日记 > 正文

Curator Cache

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(){@Overridepublic void nodeChanged() throws Exception {// TODO Auto-generated method stubif(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(){@Overridepublic void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {// TODO Auto-generated method stubif(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(){@Overridepublic void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {// TODO Auto-generated method stubswitch(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

转载于:https://www.cnblogs.com/francisYoung/p/5483777.html

相关文章:

程序可以在硬件之间发送吗_你知道硬件、软件工程师之间,还有一个固件工程师吗?...

软件跟硬件之间的界限已经越来越模糊了,那么处于这个灰色地带的,就是固件了。这就分成三类工作者。1、软件工程师一般指做图形界面的程序员,工作内容就是写C、JAVA、Web等。2、硬件工程师当然是指玩电路板的,工作内容就是画原理图…

悲催的跨平台文献管理能力

1.古老的TCP交互 邮箱、FTP、硬盘 2.用现成软件Zotero 免费、跨平台、导入后在Win福昕注释可实时同步mac看看 人生苦短,我用Zotero。。

Mastering Algorithms with C中文版附带源码说明

Mastering Algorithm with C是一本非常经典和独具个性的算法书,主要是从程序员的角度,对算法领域的基本内容,通过C语言进行源码实现,其附带的源码非常详细,对初接触这个领域的程序员很有参考价值.我特地将该书源码的使用方法做了笔记,放在这样,以便日后参考. 下面是该书的封面…

仿qq左滑删除listview_Java基于Swing和Netty仿QQ界面聊天小项目

点击上方 好好学java ,选择 星标 公众号重磅资讯、干货,第一时间送达今日推荐:硬刚一周,3W字总结,一年的经验告诉你如何准备校招!个人原创100W访问量博客:点击前往,查看更多来源&…

[BZOJ1602] [Usaco2008 Oct] 牧场行走 (LCA)

Description N头牛&#xff08;2<n<1000&#xff09;别人被标记为1到n&#xff0c;在同样被标记1到n的n块土地上吃草&#xff0c;第i头牛在第i块牧场吃草。 这n块土地被n-1条边连接。 奶牛可以在边上行走&#xff0c;第i条边连接第Ai&#xff0c;Bi块牧场&#xff0c;第i…

大数据中用到的新的数据类型bigint、decimal、smallint、tinyint

在对比oracle数据库和大数据库的时候&#xff0c;发现了几个用以存放数字的新的类型bigint、decimal、smallint、tinyint&#xff0c;为了对比之间的不同&#xff0c;我进行了统计 bigint 可以精确的表示从-263到263-1(即从-9,223,372,036,854,775,808到 9,223,372,036,854,77…

[综合面试] 计算机面试书籍与求职网站推荐

一、推荐书籍 计算机的好书挺多的&#xff0c;我买了也有四五十本&#xff0c;也花了不少钱&#xff0c;但是这些投资都是值的&#xff0c;好好看一下这些书&#xff0c;让自己找工作时的薪水涨个几千是没问题的。当然&#xff0c;也有些书是电子版的。我是c方向的&#xff0c;…

python在工厂中的运用_Python常见工厂函数用法示例

工厂函数&#xff1a;能够产生类实例的内建函数。工厂函数是指这些内建函数都是类对象&#xff0c; 当调用它们时&#xff0c;实际上是创建了一个类实例。Python中的工厂函数举例如下&#xff1a;1. int(),long(),float(),complex(),bool()>>> aint(9.9)>>> …

Java Random()函数生成指定范围的随机数

java中随机生成数字&#xff08;指定范围&#xff09; //随机获得0到&#xff08;i-1&#xff09;的一个数 int i ThreadLocalRandom.current().nextInt(i)&#xff1b;

删除链表中的重复项

方法一&#xff1a;时间优先建立一个hash_set&#xff0c;key为链表中已经遍历的节点内容&#xff0c;开始时为空。从头开始遍历链表中的节点&#xff1a;- 如果节点内容已经在hash_set中存在&#xff0c;则删除此节点&#xff0c;继续向后遍历&#xff1b;- 如果节点内容不在h…

python提取文件名数字_在Python中从文件名提取扩展名

是否有从文件名中提取扩展名的功能&#xff1f;#1楼一种选择可能是与点分开&#xff1a;>>> filename "example.jpeg">>> filename.split(".")[-1]jpeg文件没有扩展名时没有错误&#xff1a;>>> "filename".split(&…

imagick API 中文说明

下面是 imagick API 中文说明 &#xff1a; imagick 类 imagick::adaptiveblurimage 向图像中添加 adaptive 模糊滤镜 imagick::adaptiveresizeimage 自适应调整图像数据依赖关系 imagick::adaptivesharpenimage自适应锐化图像 imagick::adaptivethresholdimage 基于范围的选择…

利用dom4j将实体类转换为对应的xml报文

利用dom4j生成xml报文 目标格式&#xff1a; <?xml version"1.0" encoding"GBK"?><Packet type"REQUEST" version"1.0"><Head><RequestType>C03</RequestType><UserCode>BOCIJS</UserCode…

JSP--JavaBean

JSP 最强有力的一个方面就是能够使用 JavaBean 组件。 按照 Sun 公司的定义&#xff0c; JavaBean是一个可重复使用的软件组件。实际上 JavaBean 是一种 Java 类&#xff0c;通过封装属性和方法成为具有某种功能或者处理某些业务的对象&#xff0c;简称 Bean。 一个基本的 JSP …

python 速度矢量_最近邻搜索4D空间python快速-矢量化

For each observation in X (there are 20) I want to get the k(3) nearest neighbors.How to make this fast to support up to 3 to 4 million rows?Is it possible to speed up the loop iterating over the elements? Maybe via numpy, numba or some kind of vectoriza…

使用ajax不刷新页面获取、操作数据

在使用jsp或html时&#xff0c;利用ajax达到不刷新页面就可以获取、操作数据。 首先上代码 &#xff08;htmljs&#xff09; 在此处需要引入jquery插件 <!-- 这是页面部分 html--> <body><div style"width:100%;height:30px; float:left"><in…

C/C++面试题分享

1、指针和引用的区别&#xff1f; 答&#xff1a;引用是在C中引入的。它们之间的区别有&#xff1a; &#xff08;1&#xff09; 非空区别&#xff1a;指针可以为空&#xff0c;而引用不能为空 &#xff08;2&#xff09; 可修改区别&#xff1a;如果指针不是常指针…

js增加属性_前端js基础2

JavaScriptECMAScript(ES):规定了js的一些基础的核心知识(变量、数据类型、语法规范、操作语句等) 3/56/7 说出ES5和ES6的区别&#xff1f; DOM&#xff1a;document object model 文档对象模型&#xff0c;里面提供了一些属性和方法&#xff0c;可以让我们操作页面中的元素 BO…

附加的操作系统服务

select &#xff1a;等待I/O实现threading&#xff1a;高层次的线程接口thread&#xff1a;多线程调度dummy_threading:提供threading模块的副本接口dummy——thread&#xff1a;提供thread模块的副本接口mutiprocessing&#xff1a;在全局调度锁下使用子进程mmap&#xff1a;内…

使用myeclipse的第一步

使用myeclipse的第一步 将以下代码copy放在一个包中运行&#xff0c;然后在控制台输入任意字符&#xff0c;回车&#xff0c;然后控制台打印一串密匙&#xff0c;这里你输入的就是账号&#xff0c;控制台返回的就是注册码&#xff0c;点击MyEclipse->Subscription *** 输入…

一道题弄明白二维数组的指针

#include<stdio.h> int main(int args,char ** argv) {int map[3][3]{{1,2,3},{4,5,6},{7,8,9}};int **pMap(int **)map;printf("%d\n",map);//数组的首地址printf("%d\n",*(map1));//数组第二行首地址printf("%d\n",*map1);//数组首行的第…

Linux网络编程--进程间通信(一)

进程间通信简介&#xff08;摘自《Linux网络编程》p85&#xff09; AT&T 在 UNIX System V 中引入了几种新的进程通讯方式&#xff0c;即消息队列&#xff08; MessageQueues&#xff09;&#xff0c;信号量&#xff08; semaphores&#xff09;和共享内存&#xff08; sha…

mysql 行号_PQ获取TABLE的单一值作为条件查询MySQL返回数据

下午&#xff0c;我正爽歪歪地喝着咖啡&#xff0c;看着Power BI每秒钟刷新一次&#xff0c;静静等待某个分公司完成本月绩效任务&#xff0c;自动调用Python在钉钉群中发送喜报&#xff1a;紧接着再次调用Python将Power BI云端报告中的各分公司最新完成率数据和柱状图截图发在…

UUID的使用及其原理

今天敲项目要用UUID&#xff0c;想起之前老师告诉UUID的使用&#xff0c;但没说具体的生成逻辑&#xff0c;于是我进行了百度 首先&#xff0c;UUID的使用&#xff1a; //生成随机的UUID String uuid UUID.randomUUID().toString().replaceAll("-", "")…

链表类型题目需要用到的头文件list.h

下面是后面链表相关题目中需要用到的链表结点的定义和相关操作函数&#xff0c;参见下面的list.h文件&#xff1a; 注意链表结点的定义采用cpp的定义方式&#xff0c;它会被cpp的文件调用。比如后面删除链表重复结点的文件del_repeated_list.cpp中的编译方式&#xff1a; g -…

led计数电路实验报告_「正点原子FPGA连载」第八章 按键控制LED灯实验

1)实验平台&#xff1a;正点原子开拓者FPGA开发板2)本实例源码下载&#xff1a;请移步正点原子官网第八章 按键控制LED灯实验按键是常用的一种控制器件。生活中我们可以见到各种形式的按键&#xff0c;由于其结构简单&#xff0c;成本低廉等特点&#xff0c;在家电、数码产品、…

svn官方备份hot-backup.py强烈推荐

Author:牛班图 Date:2016/05/18 Address:suzhou --- centos 6.7默认安装的python是2.6.6&#xff0c;大家可以先查看一下自己操作系统的python版本&#xff0c;python -v&#xff1b; hot-backup.py是基于python2写的&#xff0c;python3的语法有些地方不一样&#xff0c;所以在…

用js方法做提交表单的校验

基础知识&#xff1a; 原始提交如下&#xff1a; <form action"<%basePath %>puser/register" method"post"><input placeholder"Name" name"realname"> <input type"email" placeholder"Email…

tree类型题目需要用到的头文件tree.h

下面是树类型题目需要用到的头文件tree.h,请包含在cpp文件中编译,而不是放在c文件中编译,比如查找树中两个节点的最低公共父结点的题common_parent_in_tree.cpp,编译它的方法是: g -g common_parent_in_tree.cpp -o common_parent_in_tree 下面是tree.h的内容: #include <…

用easyui动态创建一个对话框

function randomString(len) { len len || 32; var $chars ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/ var maxPos $chars.length; var pwd ; for (i 0; i < len; i) { pwd $…