掌握zookeeper事件监听机制,非常重要,可以说是跨入了进阶的门槛,只有掌握了如何监听某个节点或路径,我们才能在节点变化后,做一些我们想做的事,包括: 
1,配置文件同步 
2,主从切换 
3,分布式队列 
4,分布式锁 
5,其他

本篇我们就来看下,如何使用curator来完成监听,代码如下:

 package com.qin.curator.zk;

 import javax.sound.midi.Patch;

 import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.CuratorFrameworkFactory.Builder;
import org.apache.curator.framework.api.CuratorWatcher;
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.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.WatchedEvent;
/**
*
* 使用curator监听zookeeper节点
* @author qindongliang
* **/
public class CuratorWatch { static CuratorFramework zkclient=null;
static String nameSpace="php";
static { String zkhost="192.168.46.22:2181";//zk的host
RetryPolicy rp=new ExponentialBackoffRetry(1000, 3);//重试机制
Builder builder = CuratorFrameworkFactory.builder().connectString(zkhost)
.connectionTimeoutMs(5000)
.sessionTimeoutMs(5000)
.retryPolicy(rp);
builder.namespace(nameSpace);
CuratorFramework zclient = builder.build();
zkclient=zclient;
zkclient.start();// 放在这前面执行
zkclient.newNamespaceAwareEnsurePath(nameSpace); } public static void main(String[] args) throws Exception{ watch();
Thread.sleep(Long.MAX_VALUE); } /**
*
* 监听节点变化
*
* */
public static void watch()throws Exception{
PathChildrenCache cache = new PathChildrenCache(zkclient, "/zk", false);
cache.start(); System.out.println("监听开始/zk........");
PathChildrenCacheListener plis=new PathChildrenCacheListener() { @Override
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event)
throws Exception {
switch ( event.getType() )
{
case CHILD_ADDED:
{
System.out.println("Node added: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
} case CHILD_UPDATED:
{
System.out.println("Node changed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
} case CHILD_REMOVED:
{
System.out.println("Node removed: " + ZKPaths.getNodeFromPath(event.getData().getPath()));
break;
}
} }
};
//注册监听
cache.getListenable().addListener(plis); } }

运行后的控制台打印:

 18:33:07.722 [main] INFO  o.a.c.f.imps.CuratorFrameworkImpl - Starting
18:33:07.727 [main] DEBUG o.a.curator.CuratorZookeeperClient - Starting
18:33:07.727 [main] DEBUG org.apache.curator.ConnectionState - Starting
18:33:07.727 [main] DEBUG org.apache.curator.ConnectionState - reset
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:host.name=QINDONGLIANG.dhgatecn.msf
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.version=1.7.0_04
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.vendor=Oracle Corporation
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.home=D:\Java\jdk1.7.0_04\jre
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.class.path=D:\eclipseworkspace2yw\opzk\bin;D:\eclipseworkspace2yw\opzk\lib\curator-client-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-examples-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-framework-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-recipes-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-test-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-discovery-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-discovery-server-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\curator-x-rpc-2.6.0.jar;D:\eclipseworkspace2yw\opzk\lib\log4j-1.2.15.jar;D:\eclipseworkspace2yw\opzk\lib\zookeeper-3.4.5.jar;D:\eclipseworkspace2yw\opzk\lib\commons-io-2.1.jar
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.library.path=D:\Java\jdk1.7.0_04\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;D:/Java/jdk1.7.0_04/bin/../jre/bin/server;D:/Java/jdk1.7.0_04/bin/../jre/bin;D:/Java/jdk1.7.0_04/bin/../jre/lib/amd64;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;D:\Java\jdk1.7.0_04\bin;D:\Java\jdk1.7.0_04\jre\bin;D:\apache-ant-1.9.3\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Lenovo\Lenovo Home\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\TortoiseSVN\bin;D:\hadoop-2.2.0/bin;C:\MyProgramFiles\apache-maven-3.0.5\bin;D:\python;E:\eclipse;;.
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.io.tmpdir=C:\Users\QINDON~1\AppData\Local\Temp\
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:java.compiler=<NA>
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.name=Windows 7
18:33:07.734 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.arch=amd64
18:33:07.735 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:os.version=6.1
18:33:07.735 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.name=qindongliang
18:33:07.735 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.home=C:\Users\qindongliang
18:33:07.735 [main] INFO org.apache.zookeeper.ZooKeeper - Client environment:user.dir=D:\eclipseworkspace2yw\opzk
18:33:07.735 [main] INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=192.168.46.22:2181 sessionTimeout=5000 watcher=org.apache.curator.ConnectionState@2c351b05
18:33:07.738 [main] DEBUG org.apache.zookeeper.ClientCnxn - zookeeper.disableAutoWatchReset is false
18:33:07.760 [main-SendThread(192.168.46.22:2181)] INFO org.apache.zookeeper.ClientCnxn - Opening socket connection to server 192.168.46.22/192.168.46.22:2181. Will not attempt to authenticate using SASL (unknown error)
18:33:07.761 [main-SendThread(192.168.46.22:2181)] INFO org.apache.zookeeper.ClientCnxn - Socket connection established to 192.168.46.22/192.168.46.22:2181, initiating session
18:33:07.762 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Session establishment request sent on 192.168.46.22/192.168.46.22:2181
18:33:07.766 [main-SendThread(192.168.46.22:2181)] INFO org.apache.zookeeper.ClientCnxn - Session establishment complete on server 192.168.46.22/192.168.46.22:2181, sessionid = 0x148ac15236f0046, negotiated timeout = 5000
18:33:07.771 [main-EventThread] INFO o.a.c.f.state.ConnectionStateManager - State change: CONNECTED
18:33:08.784 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x148ac15236f0046, packet:: clientPath:null serverPath:null finished:false header:: 1,3 replyHeader:: 1,233,0 request:: '/php,F response:: s{117,117,1411712541330,1411712541330,0,5,0,0,0,3,204}
18:33:08.784 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x148ac15236f0046 after 4ms
监听开始/zk........
18:33:08.795 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x148ac15236f0046, packet:: clientPath:null serverPath:null finished:false header:: 2,3 replyHeader:: 2,233,0 request:: '/php,F response:: s{117,117,1411712541330,1411712541330,0,5,0,0,0,3,204}
18:33:08.797 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x148ac15236f0046, packet:: clientPath:null serverPath:null finished:false header:: 3,3 replyHeader:: 3,233,0 request:: '/php/zk,F response:: s{151,182,1411714954448,1411716422668,2,5,0,0,9,3,228}
18:33:08.804 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x148ac15236f0046, packet:: clientPath:/php/zk serverPath:/php/zk finished:false header:: 4,12 replyHeader:: 4,233,0 request:: '/php/zk,T response:: v{'bb,'cc,'cc334},s{151,182,1411714954448,1411716422668,2,5,0,0,9,3,228}
18:33:08.815 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x148ac15236f0046, packet:: clientPath:/php/zk/bb serverPath:/php/zk/bb finished:false header:: 5,4 replyHeader:: 5,233,0 request:: '/php/zk/bb,T response:: #6920616d2061207a6b20636f6e74656e742031,s{152,156,1411714954452,1411714982893,2,0,0,0,19,0,152}
18:33:08.816 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x148ac15236f0046, packet:: clientPath:/php/zk/cc serverPath:/php/zk/cc finished:false header:: 6,4 replyHeader:: 6,233,0 request:: '/php/zk/cc,T response:: #63313163,s{185,222,1411716737805,1411725726750,3,0,0,0,4,0,185}
18:33:08.817 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x148ac15236f0046, packet:: clientPath:/php/zk/cc334 serverPath:/php/zk/cc334 finished:false header:: 7,4 replyHeader:: 7,233,0 request:: '/php/zk/cc334,T response:: #636363,s{189,226,1411716744253,1411725775109,2,3,0,0,3,3,220}
Node added: bb
Node added: cc
Node added: cc334
18:33:10.482 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x148ac15236f0046 after 1ms
18:33:12.148 [main-SendThread(192.168.46.22:2181)] DEBUG org.apache.zookeeper.ClientCnxn - Got ping response for sessionid: 0x148ac15236f0046 after 1ms

如何使用Curator监听zookeeper事件变化的更多相关文章

  1. ionic 监听路由事件变化

    (function(){ angular.module("cakeStore", ["ngRoute", "ionic","coo ...

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

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

  3. Zookeeper命令行操作(常用命令;客户端连接;查看znode路径;创建节点;获取znode数据,查看节点内容,设置节点内容,删除节点;监听znode事件;telnet连接zookeeper)

    8.1.常用命令 启动ZK服务 bin/zkServer.sh start 查看ZK服务状态 bin/zkServer.sh status 停止ZK服务 bin/zkServer.sh stop 重启 ...

  4. .Net客户端监听ZooKeeper节点数据变化

    一个很简单的例子,用途是监听zookeeper中某个节点数据的变化,具体请参见代码中的注释 using System; using System.Collections.Generic; using ...

  5. onchange监听input值变化及input隐藏后change事件不触发的原因与解决方法(设置readonly后onchange不起作用的解决方案)

    转自:https://www.cnblogs.com/white0710/p/7338456.html 1. onchange事件监听input值变化的使用方法: <input id=" ...

  6. HTML5 oninput实时监听输入框值变化的完美方案

    在网页开发中经常会碰到需要动态监听输入框值变化的情况,如果使用 onkeydown.onkeypress.onkeyup 这个几个键盘事件来监测的话,监听不了右键的复制.剪贴和粘贴这些操作,处理组合快 ...

  7. 【转载】实时监听输入框值变化的完美方案:oninput & onpropertychange

    oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素通过用户界面发生的内容变化非常有 ...

  8. 实时监听输入框值变化:oninput & onpropertychange

    结合 HTML5 标准事件 oninput 和 IE 专属事件 onpropertychange 事件来监听输入框值变化. oninput 是 HTML5 的标准事件,对于检测 textarea, i ...

  9. js/jquery 实时监听输入框值变化的完美方案:oninput & onpropertychange

    (1)     先说jquery, 使用 jQuery 库的话,只需要同时绑定 oninput 和 onpropertychange 两个事件就可以了,示例代码: $('#username').bin ...

随机推荐

  1. 使用Python+selenium实现第一个自动化测试脚本

    原blog 一,安装Python. python官方下载地址:https://www.python.org/downloads/ 安装后点击开始菜单,在菜单最上面能找到IDLE. IDLE是pytho ...

  2. 【csp模拟赛九】--dfs3

    这道题贪心错误:直接dfs就行,枚举新开一个还是往之前的里面塞 贪心代码(80): #include<cstdio> #include<algorithm> #include& ...

  3. laravel-china 镜像停止服务

    php 的很多开发都会用到composer.然后国内的镜像又慢,很多人会选择用laravel-china的镜像. 之前一直用的很好.今天突然发现不能composer update.出现报错.WTF!! ...

  4. 齿轮 HYSBZ - 4602 (DFS实现)

    齿轮 HYSBZ - 4602 题意:很好理解就不啰嗦了. 致谢:感谢队友小明. 题解:嗯,一开始想到的是并查集,后来,就先看了另一道题,xj写dfs和暴力,就卡死了.于是来补这题了,前向星建图 题解 ...

  5. Semaphore信号量原理

    package com.maven.info.semaphore; import java.util.ArrayList; import java.util.List; import java.uti ...

  6. create an oauth app

    github可以对自己的服务进行oauth认证,创建oauth认证的方式如下: github -> Settings -> Developer settings -> Develop ...

  7. meshing-缺角正方体

    原视频下载地址:https://yunpan.cn/cqLyi92H5Akh5  访问密码 1d48

  8. 爬虫前提——正则表达式语法以及在Python中的使用

    正则表达式是用来处理字符串的强大工具,他并不是某种编程云. 正则表达式拥有独立的承受力引擎,不管什么编程语言,正则表达式的语法都是一样的. 正则表达式的匹配过程 1.一次拿出表达式和文本中的字符比较. ...

  9. 第四章 基本TCP套接字编程 第五章 TCP客户/服务器程序实例

    TCP客户与服务器进程之间发生的重大事件时间表 TCP服务器 socket() --- bind() --- listen() --- accept() --- read() --- write -- ...

  10. docker-compose 布署应用nginx中的create-react-app应用获取环境变量

    文章来源:https://www.freecodecamp.org/news/how-to-implement-runtime-environment-variables-with-create-re ...