zoukankan      html  css  js  c++  java
  • zookeeper Java API 简单操作示例

    本文主要介绍如何在java IDE中如何应用使用客户端与zookeeper服务器通信。

      首先搭建maven环境,并在pom文件中加入zookeeper引用包:

    <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.4.9</version>
    </dependency>

      如果从maven中引用失败,也不比灰心,在官网上下载zookeeper-3.4.9.tar.gz包,解压后里面包含zookeeper-3.4.9.jar包,在工程中引入这个包即可。

      在工程中新建TestZookeeper.java文件,代码如下:

      1 package com.unionpay.zookeeperDemo;
      2 
      3 import java.io.IOException;
      4 
      5 import org.apache.zookeeper.CreateMode;
      6 import org.apache.zookeeper.KeeperException;
      7 import org.apache.zookeeper.WatchedEvent;
      8 import org.apache.zookeeper.Watcher;
      9 import org.apache.zookeeper.ZooDefs.Ids;
     10 import org.apache.zookeeper.ZooKeeper;
     11 
     12 public class TestZookeeper {
     13     public static void main(String[] args){
     14         ZooKeeper zk = null;
     15         
     16         try{
     17             System.out.println("......");
     18             System.out.println("Starting to connencting zookeeper......");
     19             
     20             String connectString  = "127.0.0.1:2181";
     21             int sessionTimeout = 2000;
     22         
     23             Watcher watcher = new Watcher(){
     24 
     25                 @Override
     26                 public void process(WatchedEvent event) {
     27                     if(event.getType() == null || "".equals(event.getType())){
     28                         return;
     29                     }
     30                     System.out.println("已经触发了" + event.getType() + "事件!");
     31                 }        
     32             };
     33             zk = new ZooKeeper(connectString, sessionTimeout, watcher);
     34             
     35 /*            zk = new ZooKeeper(connectString, sessionTimeout, new Watcher(){
     36                 public void process(WatchedEvent event){
     37                     if(event.getType()==null | "".equals(event.getType())){
     38                         return;
     39                     }
     40                     System.out.println("已经触发了" + event.getType() + "事件!");
     41                 }
     42             });*/
     43             
     44             System.out.println("Zookeeper Connected Successfully!");
     45             
     46             Thread.currentThread().sleep(10001);
     47             
     48             System.out.println("......");
     49             System.out.println("开始创建根目录节点/tmp_root_path...");
     50             zk.exists("/tmp_root_path", true);
     51             zk.create("/tmp_root_path", "我是根目录节点/tmp_root_path".getBytes("utf-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
     52             System.out.println("根目录节点/tmp_root_path创建成功");
     53             
     54             Thread.currentThread().sleep(10001);
     55             
     56             System.out.println("......");
     57             System.out.println("开始创建第一个子目录节点/tmp_root_path/childPath1...");
     58             zk.exists("/tmp_root_path/childPath1", true);
     59             zk.create("/tmp_root_path/childPath1", "我是第一个子目录/tmp_root_path/childPath1".getBytes("utf-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
     60             System.out.println("第一个子目录节点/tmp_root_path/childPath1创建成功");
     61             
     62             Thread.currentThread().sleep(10001);
     63             
     64             System.out.println("......");
     65             System.out.println("开始修改第一个子目录节点/tmp_root_path/childPaht1的数据......");
     66             //通过getData 或 exists 方法触发watcher事件
     67             zk.getData("/tmp_root_path/childPath1", true, null);
     68             zk.setData("/tmp_root_path/childPath1", "我是修改后的第一个子目录/tmp_root_path/childPath1".getBytes("utf-8"), -1);
     69             //version参数指定要更新的数据版本,如果version和真实的版本数据不同,则更新操作失败,当setData中设置版本为-1时,忽略版本检测
     70             System.out.println("修改第一个子目录节点/tmp_root_path/childPath1数据成功!");
     71             
     72             Thread.currentThread().sleep(10001);
     73             
     74             System.out.println("......");
     75             
     76             System.out.println("获取根目录节点状态......");
     77             System.out.println(zk.exists("/tmp_root_path", true));
     78             System.out.println("根目录节点获取成功");
     79             
     80             Thread.currentThread().sleep(10001);
     81             
     82             System.out.println("......");
     83             System.out.println("开始创建第二个子目录节点/tmp_root_path/childPath2...");
     84             zk.exists("/tmp_root_path/childPath2", true);
     85             zk.create("/tmp_root_path/childPath2", "我是第二个子目录节点/tmp_root_path/childPath2".getBytes("utf-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
     86             System.out.println("第二个子目录节点/tmp_root_path/childPath2创建成功");
     87             
     88             Thread.currentThread().sleep(10001);
     89             
     90             
     91             System.out.println("......");
     92             System.out.println("获取第二个子目录节点数据......");
     93             System.out.println(new String(zk.getData("/tmp_root_path/childPath2", true, null)));
     94             System.out.println("成功获取第二个子目录节点数据");
     95             
     96             
     97             Thread.currentThread().sleep(10001);
     98             
     99             System.out.println("......");
    100             System.out.println("开始获取根目录节点状态");
    101             System.out.println(zk.exists("/tmp_root_path", true));
    102             System.out.println("根目录节点状态获取成功");
    103             
    104             Thread.currentThread().sleep(10001);
    105             
    106             System.out.println("开始删除第一个子目录节点/tmp_root_path/childPath1...");
    107             /*zk.getData("/tmp_root_path/childPath1", true, null);*/
    108             zk.exists("/tmp_root_path/childPath1", true);
    109             zk.delete("/tmp_root_path/childPath1", -1);
    110             System.out.println("第一个子目录节点/tmp_root_path/childPath1删除成功");
    111             
    112             Thread.currentThread().sleep(10001);
    113             
    114             System.out.println("开始获取根目录节点状态");
    115             System.out.println(zk.exists("/tmp_root_path", true));
    116             System.out.println("根目录节点状态获取成功");
    117             
    118             Thread.currentThread().sleep(10001);
    119             
    120             System.out.println("开始删除第二个子目录节点/tmp_root_path/childPath2......");
    121             zk.delete("/tmp_root_path/childPath2", -1);
    122             System.out.println("第二个子目录节点/tmp_root_path/childPath2删除成功");
    123             
    124             Thread.currentThread().sleep(10001);
    125             
    126             System.out.println("......");
    127             System.out.println("开始获取根目录节点状态");
    128             System.out.println(zk.exists("/tmp_root_path", true));
    129             System.out.println("根目录节点状态获取成功");
    130             
    131             Thread.currentThread().sleep(10001);
    132             
    133             System.out.println("开始删除根目录节点/tmp_root_path......");
    134             zk.delete("/tmp_root_path", -1);
    135             System.out.println("删除根目录节点/tmp_root_path成功");
    136             
    137             Thread.currentThread().sleep(10001);
    138             System.out.println("查看根目录节点状态");
    139             System.out.println(zk.exists("/tmp_root_path", true));
    140             System.out.println("根目录节点状态获取成功");
    141             
    142             Thread.currentThread().sleep(10001);
    143         }catch(IOException | KeeperException | InterruptedException e){
    144             e.printStackTrace();
    145         }finally{
    146             if(zk != null){
    147                 try{
    148                     zk.close();
    149                     System.out.println("关闭Zookeeper连接成功");
    150                 }catch(InterruptedException e){
    151                     e.printStackTrace();
    152                 }
    153             }
    154         }
    155     }
    156 }

      然后启动zookeeper服务器:

    bash server1/bin/zkServer.sh start
    
    bash server2/bin/zkServer.sh start
    
    bash server3/bin/zkServer.sh start

      当zookeeper集群成功启动后,运行TestZookeeper.java文件,运行结果如下:

     1 ......
     2 Starting to connencting zookeeper......
     3 log4j:WARN No appenders could be found for logger (org.apache.zookeeper.ZooKeeper).
     4 log4j:WARN Please initialize the log4j system properly.
     5 log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
     6 Zookeeper Connected Successfully!
     7 已经触发了None事件!
     8 ......
     9 开始创建根目录节点/tmp_root_path...
    10 已经触发了NodeCreated事件!
    11 根目录节点/tmp_root_path创建成功
    12 ......
    13 开始创建第一个子目录节点/tmp_root_path/childPath1...
    14 已经触发了NodeCreated事件!
    15 第一个子目录节点/tmp_root_path/childPath1创建成功
    16 ......
    17 开始修改第一个子目录节点/tmp_root_path/childPaht1的数据......
    18 已经触发了NodeDataChanged事件!
    19 修改第一个子目录节点/tmp_root_path/childPath1数据成功!
    20 ......
    21 获取根目录节点状态......
    22 30064771083,30064771083,1487902036450,1487902036450,0,1,0,0,35,1,30064771084
    23 
    24 根目录节点获取成功
    25 ......
    26 开始创建第二个子目录节点/tmp_root_path/childPath2...
    27 已经触发了NodeCreated事件!
    28 第二个子目录节点/tmp_root_path/childPath2创建成功
    29 ......
    30 获取第二个子目录节点数据......
    31 我是第二个子目录节点/tmp_root_path/childPath2
    32 成功获取第二个子目录节点数据
    33 ......
    34 开始获取根目录节点状态
    35 30064771083,30064771083,1487902036450,1487902036450,0,2,0,0,35,2,30064771086
    36 
    37 根目录节点状态获取成功
    38 开始删除第一个子目录节点/tmp_root_path/childPath1...
    39 已经触发了NodeDeleted事件!
    40 第一个子目录节点/tmp_root_path/childPath1删除成功
    41 开始获取根目录节点状态
    42 30064771083,30064771083,1487902036450,1487902036450,0,3,0,0,35,1,30064771087
    43 
    44 根目录节点状态获取成功
    45 开始删除第二个子目录节点/tmp_root_path/childPath2......
    46 已经触发了NodeDeleted事件!
    47 第二个子目录节点/tmp_root_path/childPath2删除成功
    48 ......
    49 开始获取根目录节点状态
    50 30064771083,30064771083,1487902036450,1487902036450,0,4,0,0,35,0,30064771088
    51 
    52 根目录节点状态获取成功
    53 开始删除根目录节点/tmp_root_path......
    54 已经触发了NodeDeleted事件!
    55 删除根目录节点/tmp_root_path成功
    56 查看根目录节点状态
    57 null
    58 根目录节点状态获取成功
    59 关闭Zookeeper连接成功

       在代码中,我们可以看到zk.exists("****",true),不断出现,目的是为了监听相应的znode 修改和删除事件,从结果中我们也不难看出监听结果“已经触发了NodeDataChanged事件!”和“已经触发了NodeDeleted事件!”。之所以要对每个节点多次执行zk.exists(),这是因为在zookeeper机制下,zk.exists()方法、zk.get()方法和zk.getChildren()方法仅仅监控对应节点的一次变化(数据变化或者子节点数目发生变化)。

      zookeeper可以监控到的事件类型:

    • ZOO_CREATED_EVENT:节点创建事件,需要watch一个不存在的节点,当此节点被创建时,通过exist()设置可以触发该对该事件的监控;
    • ZOO_DELETED_EVENT:节点删除事件,此watch通过exists()或者get()设置监控;
    • ZOO_CHANGED_EVENT:节点数据改变事件,此watch通过exists()或者get()设置监控;
    • ZOO_CHILD_EVENT:子节点列表改变事件,此watch通过getChildren()设置监控;
    • ZOO_SESSION_EVENT:会话失效事件,客户端与服务端断开或者重新连结时触发;
    • ZOO_NOWATCHING_EVENT:watch移除事件,服务端因为某些原因不再为客户端watch节点的触发

    参考文献:

  • 相关阅读:
    集RTMP, HLS, FLV, WebSocket 于一身的网页直播/点播播放器EasyPlayer.js引用videojs无法自动播放问题解决
    HLS播放器RTSP播放器支持8K播放且低延时高并发全功能流媒体播放器EasyPlayer搭建之HTML中 px,em,rem该如何区别?
    网页全终端安防视频流媒体播放器EasyPlayer.js如何实现在web浏览器播放H.265编码视频?
    网页全终端视频流媒体视频直播/点播播放器EasyPlayer.js实现WEB播放H265/HEVC视频方案介绍
    网页全终端视频流媒体播放器EasyPlayer之使用 nginx 和 rtmp 插件搭建视频直播和点播服务器
    车辆实时监控项目中数字摄像头和模拟摄像头的运用、区别及优势分析
    音视频流媒体服务器直播点播平台在车辆实时监控系统中如何做用户观看限制?
    如何借助CDN解决在线教育带宽小、访问大、网点分布不均等问题
    关于区块链,看看诺奖得主是如何评说的!
    区块链也有随机性!
  • 原文地址:https://www.cnblogs.com/jxwch/p/6437319.html
Copyright © 2011-2022 走看看