`
qindongliang1922
  • 浏览: 2181019 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
7265517b-f87e-3137-b62c-5c6e30e26109
证道Lucene4
浏览量:117401
097be4a0-491e-39c0-89ff-3456fadf8262
证道Hadoop
浏览量:125817
41c37529-f6d8-32e4-8563-3b42b2712a50
证道shell编程
浏览量:59804
43832365-bc15-3f5d-b3cd-c9161722a70c
ELK修真
浏览量:71227
社区版块
存档分类
最新评论

如何使用Curator监听zookeeper事件变化

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

散仙,在以前的文章里面有写过使用zookeeper原生的api,监听zk节点变化,那么本篇我们就来看下,如何使用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


用到的jar包如下所示:




  • 大小: 90.8 KB
分享到:
评论
8 楼 m475757 2016-09-23  
标题学错了一个字母。。。。。。。。。。。
7 楼 宋建勇 2015-01-31  
qindongliang1922 写道
宋建勇 写道
这工具着实不赖啊!

宋建勇 写道
这工具着实不赖啊!

你们也用了吗,操作zk很方便!

是的,服务发布时用了ZK
6 楼 qindongliang1922 2015-01-30  
宋建勇 写道
这工具着实不赖啊!

宋建勇 写道
这工具着实不赖啊!

你们也用了吗,操作zk很方便!
5 楼 宋建勇 2015-01-30  
这工具着实不赖啊!
4 楼 qindongliang1922 2014-10-20  
bluky999 写道
qindongliang1922 写道
bluky999 写道
LZ 还继续更新么?


哈哈,你们也用这个了吗


是的,看起来你是边实践边记录啊,很不错的经验分享; 多多交流分布式主题啊 。




当然可以,互相学习嘛,加我QQ交流吧,  951514291 
3 楼 bluky999 2014-10-20  
qindongliang1922 写道
bluky999 写道
LZ 还继续更新么?


哈哈,你们也用这个了吗


是的,看起来你是边实践边记录啊,很不错的经验分享; 多多交流分布式主题啊 。
2 楼 qindongliang1922 2014-10-20  
bluky999 写道
LZ 还继续更新么?


哈哈,你们也用这个了吗
1 楼 bluky999 2014-10-20  
LZ 还继续更新么?

相关推荐

    zookeeper 使用 Curator 示例监听、分布式锁

    Curator 提供了事件监听器,可以注册到 ZooKeeper 路径上,当该路径下发生创建、删除、数据改变等事件时,监听器会被触发。这在分布式系统中非常有用,例如监控配置变化、节点状态变更等。 四、Curator 实现分布式...

    curator_zookeeper需要的jar

    在Java开发中,Apache Curator 是一个非常重要的工具库,它为使用Zookeeper提供了一套高级API,简化了Zookeeper的使用。标题“curator_zookeeper需要的jar”表明我们正在讨论Curator与Zookeeper集成时所需的JAR文件...

    zookeeper客户端curator操作示例

    可以注册监听器来接收ZooKeeper的各种事件,如节点创建、删除、数据更改等,这使得实时监控和响应ZooKeeper状态变化变得简单。 3. **数据和节点操作**: Curator提供了创建、读取、更新、删除(CRUD)ZooKeeper...

    zookeeper学习之三(Curator客户端)

    Curator客户端是Apache Curator框架的一部分,该框架为开发人员提供了一系列高级API和工具,用于处理常见的ZooKeeper用例,降低了使用ZooKeeper的复杂性。以下是对Curator客户端及其主要特性的详细阐述: 1. **连接...

    项目加入zookeeper的依赖包(Curator框架)

    - 监听器:注册`CuratorWatcher`监听Zookeeper节点的变化。 总的来说,Curator框架极大地简化了Zookeeper的使用,提供了丰富的功能和易于使用的API,使开发者能够更专注于业务逻辑而不是底层的协调细节。在项目中...

    5、zookeeper的java -Curator(服务注册与发现)

    4. 服务缓存:为了提高效率,`ServiceCache`可以缓存特定服务的实例列表,监听Zookeeper的变化并保持最新。启动`ServiceCache`并调用`getInstance()`或`getAllInstances()`获取服务实例。 Curator的`ServiceCache`...

    Zookeeper客户端Curator Framework使用代码

    Curator的Cache机制可以监听Zookeeper数据变化,例如监听节点数据变更: ```java curator.getCuratorListenable().addListener(new CuratorListener() { @Override public void eventReceived(CuratorFramework...

    使用curator实现zookeeper锁服务的示例分享

    Curator是Netflix开源的一个用于简化Zookeeper使用的Java客户端库,它提供了很多高级功能,包括分布式锁、事件监听、配方等。在这个示例中,我们将使用Curator的`InterProcessMutex`类来实现分布式互斥锁(Mutex)。...

    maven-zookeeper

    Curator提供了一套完整的API,用于创建、删除、检查Zookeeper节点,以及监听节点变化等操作。它还包括了一些高级特性,如recipes,如分布式锁、分布式计数器、领导选举等,这些recipes是解决分布式系统常见问题的...

    ZooKeeper-Curator:zookeeper的curator客户端

    7. **使用ZooKeeper-Curator** - 配置:设置ZooKeeper服务器的连接字符串,并创建`CuratorFramework`实例。 - 初始化:启动`CuratorFramework`实例并连接到ZooKeeper服务器。 - 操作:使用`CuratorFramework`提供...

    Zookeeper开源客户端框架Curator简介与示例

    Curator 是一个基于 ZooKeeper 的开源客户端框架,它为 ZooKeeper 提供了高级抽象和功能,使得开发人员能够更方便地使用 ZooKeeper。 **Curator 框架概述** Curator 包含多个模块,如 ZooKeeper 客户端连接管理、...

    Zookeeper 原生api zkClient Curator操作

    在Java开发中,我们通常使用三种方式来操作Zookeeper:原生API、zkClient和Curator。接下来,我们将详细探讨这三种方式。 **一、Zookeeper原生API** Zookeeper提供了Java API,可以直接与Zookeeper服务器进行交互...

    zookeeper Java api - curator 5.6.0

    5. **监控与事件**:Curator 支持监听节点的变化,通过注册 `PathChildrenCache` 或 `DataTreeCache` 可以实时监控节点或数据的变化。例如: ```java PathChildrenCache cache = new PathChildrenCache(client, "/...

    Curator的JAR包

    6. **缓存**:Curator提供了一种数据缓存机制,可以自动监听ZooKeeper中的数据变化并更新本地缓存,减少了对ZooKeeper的频繁访问,提高了性能。 `Apache Curator入门实战.docx`文档很可能是对如何使用Curator进行...

    一文彻底理解ZooKeeper分布式锁的实现原理

    Curator是Apache的一个项目,提供了丰富的工具和策略来简化ZooKeeper的使用。在分布式锁的实现中,Curator不仅帮助创建和管理临时顺序节点,还负责监听和通知机制,使得客户端能方便地实现加锁和解锁操作。 四、...

    springboot-zookeeper-curator.rar

    此外,Curator还提供了如节点监控、事件监听、队列管理、分布式计数器等多种实用功能,你可以根据实际需求进行选择和应用。 在实际项目中,Zookeeper Curator的整合能够帮助我们构建更加稳定、可扩展的分布式系统。...

    zk使用curator实现分布式锁

    在分布式系统中,确保数据的一致性和正确性是至关重要的,而ZooKeeper与Curator的结合使用就是解决这一问题的有效方案。ZooKeeper是一个高度可靠的分布式协调服务,它提供了诸如分布式锁、队列和配置管理等核心功能...

    zookeeper_demo maven项目:包含原生API、zkclient、Curator操作

    Curator的出现降低了使用Zookeeper的复杂性,使得开发者可以专注于业务逻辑,而无需关心底层实现的复杂性。 4. **集群配置** 在`zookeeper_demo`项目中,展示了如何配置和连接Zookeeper集群。在分布式环境中,...

    4、zookeeper的java三种客户端介绍-Curator(crud、事务操作、监听、分布式计数器、分布式锁)

    总结来说,Apache Curator作为Zookeeper的Java客户端,通过提供高级API和各种预定义的解决方案,显著降低了开发者的使用难度,使其能够更高效地利用Zookeeper实现分布式系统的协调需求。在选择Zookeeper客户端时,...

    3天全面深入学习zookeeper视频教程

    zookeeper 事件监听机制 zookeeper 集群搭建 一致性协议:zab协议 zookeeper的leader选举 observer角色及其配置 zookeeperAPI连接集群 zookeeper 开源客户端curator介绍 zookeeper四字监控命令 zookeeper图形化的...

Global site tag (gtag.js) - Google Analytics