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

代码如下:

  1. package com.iflytek.cpcloud.zookeeper;
  2.  
  3. import java.io.IOException;
  4. import java.util.List;
  5.  
  6. import org.apache.commons.logging.Log;
  7. import org.apache.commons.logging.LogFactory;
  8. import org.apache.log4j.PropertyConfigurator;
  9. import org.apache.zookeeper.KeeperException;
  10. import org.apache.zookeeper.WatchedEvent;
  11. import org.apache.zookeeper.Watcher;
  12. import org.apache.zookeeper.ZooKeeper;
  13. import org.apache.zookeeper.Watcher.Event.EventType;
  14.  
  15. public class WatchClient implements Runnable {
  16.  
  17. private static final Log LOG = LogFactory.getLog(WatchClient.class);
  18. public static final int CLIENT_PORT = 2181;
  19. public static final String PATH = "/app1";// 所要监控的结点
  20. private static ZooKeeper zk;
  21. private static List<String> nodeList;// 所要监控的结点的子结点列表
  22.  
  23. public static void main(String[] args) throws Exception {
  24. PropertyConfigurator.configure("F:\\test\\conf\\log4j.properties");
  25. WatchClient client = new WatchClient();
  26. Thread th = new Thread(client);
  27. th.start();
  28. }
  29.  
  30. public WatchClient() throws IOException {
  31.  
  32. zk = new ZooKeeper("192.168.255.133:" + CLIENT_PORT, 21810,
  33. new Watcher() {
  34. public void process(WatchedEvent event) {
  35. }
  36. });
  37. }
  38.  
  39. /**
  40. * 设置watch的线程
  41. */
  42. @Override
  43. public void run() {
  44.  
  45. Watcher wc = new Watcher() {
  46. @Override
  47. public void process(WatchedEvent event) {
  48. // 结点数据改变之前的结点列表
  49. List<String> nodeListBefore = nodeList;
  50. // 主结点的数据发生改变时
  51. if (event.getType() == EventType.NodeDataChanged) {
  52. LOG.info("Node data changed:" + event.getPath());
  53. }
  54. if (event.getType() == EventType.NodeDeleted){
  55. LOG.info("Node deleted:" + event.getPath());
  56. }
  57. if(event.getType()== EventType.NodeCreated){
  58. LOG.info("Node created:"+event.getPath());
  59. }
  60.  
  61. // 获取更新后的nodelist
  62. try {
  63. nodeList = zk.getChildren(event.getPath(), false);
  64. } catch (KeeperException e) {
  65. System.out.println(event.getPath()+" has no child, deleted.");
  66. } catch (InterruptedException e) {
  67. e.printStackTrace();
  68. }
  69. List<String> nodeListNow = nodeList;
  70. // 增加结点
  71. if (nodeListBefore.size() < nodeListNow.size()) {
  72. for (String str : nodeListNow) {
  73. if (!nodeListBefore.contains(str)) {
  74. LOG.info("Node created:" + event.getPath() + "/" + str);
  75. }
  76. }
  77. }
  78. }
  79. };
  80.  
  81. /**
  82. * 持续监控PATH下的结点
  83. */
  84. while (true) {
  85. try {
  86. zk.exists(PATH, wc);//所要监控的主结点
  87. } catch (KeeperException | InterruptedException e) {
  88. e.printStackTrace();
  89. }
  90. try {
  91. nodeList = zk.getChildren(PATH, wc);
  92. } catch (KeeperException | InterruptedException e) {
  93. e.printStackTrace();
  94. }
  95. // 对PATH下的每个结点都设置一个watcher
  96.  
  97. for (String nodeName : nodeList) {
  98. try {
  99. zk.exists(PATH + "/" + nodeName, wc);
  100. } catch (KeeperException | InterruptedException e) {
  101. e.printStackTrace();
  102. }
  103. }
  104.  
  105. try {
  106. Thread.sleep(3000);// sleep一会,减少CUP占用率
  107. } catch (InterruptedException e) {
  108. e.printStackTrace();
  109. }
  110. }
  111. }
  112. }

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

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <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">
  4.  
  5. <modelVersion>4.0.0</modelVersion>
  6.  
  7. <groupId>com.iflytek.cpcloud</groupId>
  8. <artifactId>zookeeper-test</artifactId>
  9. <version>0.1.0-SNAPSHOT</version>
  10.  
  11. <dependencies>
  12. <dependency>
  13. <groupId>log4j</groupId>
  14. <artifactId>log4j</artifactId>
  15. <version>1.2.17</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>commons-logging</groupId>
  19. <artifactId>commons-logging</artifactId>
  20. <version>1.1.1</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>commons-cli</groupId>
  24. <artifactId>commons-cli</artifactId>
  25. <version>1.2</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>junit</groupId>
  29. <artifactId>junit</artifactId>
  30. <version>4.11</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.apache.zookeeper</groupId>
  34. <artifactId>zookeeper</artifactId>
  35. <version>3.4.5</version>
  36. </dependency>
  37. </dependencies>
  38.  
  39. <build>
  40. <plugins>
  41. <plugin>
  42. <artifactId>maven-assembly-plugin</artifactId>
  43. <version>2.2-beta-5</version>
  44. <configuration>
  45. <descriptorRefs>
  46. <descriptorRef>jar-with-dependencies</descriptorRef>
  47. </descriptorRefs>
  48. </configuration>
  49. </plugin>
  50. <plugin>
  51. <groupId>org.apache.maven.plugins</groupId>
  52. <artifactId>maven-compiler-plugin</artifactId>
  53. <version>2.3.2</version>
  54. <configuration>
  55. <source>1.6</source>
  56. <target>1.6</target>
  57. <encoding>UTF-8</encoding>
  58. </configuration>
  59. </plugin>
  60. </plugins>
  61. </build>
  62.  
  63. </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. 自己封装的一个简易的二维表类SimpleTable

    在QT中,QTableWidget处理二维表格的功能很强大(QTableView更强大),但有时我们只想让它显示少量数据(文字和图片),这时,使用QTableWidget就有点不方便了(个人感觉).所 ...

  2. linux系统怎么改为中文版(转)

    linux系统安装好后怎么改为中文版呢?今天就跟大家介绍下linux系统改为中文版的方法,希望能帮助到大家! 以下是linux系统改为中文版的四种方法,一起来看看: 方法1:写入环境变量 echo & ...

  3. Make a travel blog by Blogabond the theme of wordpress

    We can record our place which we have ever went.If you want to know any more you can visit :http://w ...

  4. 【POJ 1679 The Unique MST】最小生成树

    无向连通图(无重边),判断最小生成树是否唯一,若唯一求边权和. 分析生成树的生成过程,只有一个圈内出现权值相同的边才会出现权值和相等但“异构”的生成树.(并不一定是最小生成树) 分析贪心策略求最小生成 ...

  5. HDOJ-1041 Computer Transformation(找规律+大数运算)

    http://acm.hdu.edu.cn/showproblem.php?pid=1041 有一个初始只有一个1的串 每次都按①0 -> 10;②1 -> 01;这两条规则进行替换 形如 ...

  6. User has no SELECT privilege on V$SESSION

         今天是2013-09-20,最近心情一直很差,但是也不能不学习啊,无论怎么样,自己学到 的东西永远都是自己的.加油! 使用dbms_xplan.display_cursor function ...

  7. javacript 面向对象

    1.对象 使用Object创建对象 var p = new Object(); p.name = 'jason'; p.sayName = function(){ alert(this.name); ...

  8. Hadoop 3、Hadoop 分布式存储系统 HDFS

    HDFS是Hadoop Distribute File System 的简称,也就是Hadoop的一个分布式文件系统. 一.HDFS的优缺点 1.HDFS优点: a.高容错性 .数据保存多个副本 .数 ...

  9. Hibernate缓存、组件、继承映射

    Hibernate缓存.组件.继承映射 三种状态: 临时状态:不受session管理,没有提交到数据库:没有执行sql之前,new对象的时候: 持久化状态:受session管理,提交到数据库:正在执行 ...

  10. 移植busybox-1.21.1

    busybox官网:www.busybox.net 1.解压 # tar jxvf busybox-1.21.1.tar.bz2 2.配置 # cd busybox-1.21.1 # make men ...