众所周知,ZooKeeper中的ZNode是树形结构,现在我需要给/app1结点设置watcher,监听/app1下增减、删除和修改的结点,并将相应的事件使用log4j记录到日志文件中。ZNode的变化可以直接通过event.getType来获取。使用zk.exists(PATH, wc);来为PATH结点设置watcher,所有结点都可以使用wc做watcher。

代码如下:

package com.iflytek.cpcloud.zookeeper;

import java.io.IOException;
import java.util.List; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType; public class WatchClient implements Runnable { private static final Log LOG = LogFactory.getLog(WatchClient.class);
public static final int CLIENT_PORT = 2181;
public static final String PATH = "/app1";// 所要监控的结点
private static ZooKeeper zk;
private static List<String> nodeList;// 所要监控的结点的子结点列表 public static void main(String[] args) throws Exception {
PropertyConfigurator.configure("F:\\test\\conf\\log4j.properties");
WatchClient client = new WatchClient();
Thread th = new Thread(client);
th.start();
} public WatchClient() throws IOException { zk = new ZooKeeper("192.168.255.133:" + CLIENT_PORT, 21810,
new Watcher() {
public void process(WatchedEvent event) {
}
});
} /**
* 设置watch的线程
*/
@Override
public void run() { Watcher wc = new Watcher() {
@Override
public void process(WatchedEvent event) {
// 结点数据改变之前的结点列表
List<String> nodeListBefore = nodeList;
// 主结点的数据发生改变时
if (event.getType() == EventType.NodeDataChanged) {
LOG.info("Node data changed:" + event.getPath());
}
if (event.getType() == EventType.NodeDeleted){
LOG.info("Node deleted:" + event.getPath());
}
if(event.getType()== EventType.NodeCreated){
LOG.info("Node created:"+event.getPath());
} // 获取更新后的nodelist
try {
nodeList = zk.getChildren(event.getPath(), false);
} catch (KeeperException e) {
System.out.println(event.getPath()+" has no child, deleted.");
} catch (InterruptedException e) {
e.printStackTrace();
}
List<String> nodeListNow = nodeList;
// 增加结点
if (nodeListBefore.size() < nodeListNow.size()) {
for (String str : nodeListNow) {
if (!nodeListBefore.contains(str)) {
LOG.info("Node created:" + event.getPath() + "/" + str);
}
}
}
}
}; /**
* 持续监控PATH下的结点
*/
while (true) {
try {
zk.exists(PATH, wc);//所要监控的主结点
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
try {
nodeList = zk.getChildren(PATH, wc);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
// 对PATH下的每个结点都设置一个watcher for (String nodeName : nodeList) {
try {
zk.exists(PATH + "/" + nodeName, wc);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
} try {
Thread.sleep(3000);// sleep一会,减少CUP占用率
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

该项目使用maven构建。pom.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.iflytek.cpcloud</groupId>
<artifactId>zookeeper-test</artifactId>
<version>0.1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.5</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build> </project>

【Apache ZooKeeper】为ZNode设置watcher的更多相关文章

  1. ERROR org.apache.zookeeper.ClientCnxn:532 - Error while calling watcher

    一.背景 使用zookeeper操作时提示这个错误信息 ERROR org.apache.zookeeper.ClientCnxn: - Error while calling watcher jav ...

  2. 【Apache ZooKeeper】命令行zkCli.sh使用指南

    ZooKeeper命令行 原文                   http://blog.csdn.net/ganglia/article/details/11606807 ZooKeeper客户端 ...

  3. 2.动手实操Apache ZooKeeper

    Tips 做一个终身学习的人! 日拱一卒,功不唐捐. 在本节中,我们将讲解如何下载并安装Apache ZooKeeper,以便我们可以直接开始使用ZooKeeper. 本部分旨在通过提供详细的安装和使 ...

  4. Java实现ZooKeeper的zNode监控

    上一篇文章已经完成了ZooKeeper的基本搭建和使用的介绍,现在开始用代码说话.参考 https://zookeeper.apache.org/doc/current/javaExample.htm ...

  5. 如果你还不知道Apache Zookeeper?你凭什么拿大厂Offer!!

    很多同学或多或少都用到了Zookeeper,并知道它能实现两个功能 配置中心,实现表分片规则的统一配置管理 注册中心,实现sharding-proxy节点的服务地址注册 那么Zookeeper到底是什 ...

  6. Apache Zookeeper Java客户端Curator使用及权限模式详解

    这篇文章是让大家了解Zookeeper基于Java客户端Curator的基本操作,以及如何使用Zookeeper解决实际问题. Zookeeper基于Java访问 针对zookeeper,比较常用的J ...

  7. Apache ZooKeeper原理剖析及分布式理论名企高频面试v3.7.0

    概述 **本人博客网站 **IT小神 www.itxiaoshen.com 定义 Apache ZooKeeper官网 https://zookeeper.apache.org/ 最新版本3.7.0 ...

  8. 微服务架构 | 3.3 Apache Zookeeper 注册中心

    @ 目录 前言 1. Zookeeper 基础知识 1.1 Zookeeper 是什么 1.2 Zookeeper 的数据结构 1.3 Watcher 机制 1.4 常见应用场景分析 1.5 Zook ...

  9. ZooKeeper - Perl bindings for Apache ZooKeeper Perl绑定用于 Apache ZooKeeper

    ZooKeeper - Perl bindings for Apache ZooKeeper Perl绑定用于 Apache ZooKeeper 监控 master/slave 需要使用zk的临时节点 ...

随机推荐

  1. 善待Redis里的数据--Unable to validate object

    又是一篇关于姿势的文章,为什么是”又”呢?因为上个星期刚写完一篇关于Apache Commons Pool的正确使用姿势的文章,点击此处阅读. Redis为我们提供便利的同时,我们也要善待里面的数据 ...

  2. Erlang语言介绍

    Erlang (/ˈɜrlæŋ/ er-lang) is a general-purpose concurrent, garbage-collected programming language an ...

  3. cocos2dx lua 学习笔记(一)

    macosx 安装 lua curl -R -O http://www.lua.org/ftp/lua-5.1.4.tar.gz tar zxf lua-5.1.4.tar.gz cd lua-5.1 ...

  4. 如何实现在O(n)时间内排序,并且空间复杂度为O(1)

    对于常见的排序算法,很难做到在O(n)时间内排序,并且空间复杂度为O(1),这里提供了一种方法可以达到要求. 可以使用哈希排序的思想,也就是将所有的数哈希到哈希表中,实现排序.具体的算法思想是,求出这 ...

  5. HTML 4.01 符号实体

    HTML 4.01 符号实体 http://www.w3school.com.cn/tags/html_ref_symbols.html

  6. Android 上多方式定位元素(python)

    Android 上多方式定位元素(python) 在学习实际UI自动化测试的时候,首先就需要定位元素,然而定位元素也是最头疼的地方,因为元素各种控件名称的缺失会影响元素的准确定位.下面针对Androi ...

  7. SQL Server 2008 R2如何开启数据库的远程连接

    SQL Server 2008 R2如何开启数据库的远程连接 SQL Server 2005以上版本默认是不允许远程连接的,如果想要在本地用SSMS连接远程服务器上的SQL Server 2008,远 ...

  8. Ubuntu 13.10 下安装node

    1.首先更新Ubuntu在线包:sudo apt-get update && sudo apt-get dist-upgrade, 2.默认Ubuntu已经安装python的,具体版本 ...

  9. 取得网站的IP 地址

    select utl_inaddr.get_host_address('smtp.163.com') ipaddress from dual;

  10. zoj 1067

    输入一组RGB颜色列表,每行一个颜色,是三个从0~255的整数 前16行是目标颜色组,-1 -1 -1表示结束   16组颜色以后接下来的几行是需要判断的,看它和哪个颜色的距离D最小,找出这个对应的颜 ...