04 ZooKeeperAPI实战


传送门:


04 ZooKeeperAPI实战

1. IDEA环境搭建

  如果跟我一样还未安装IDEA与环境配置的,需要先进行这些。安装IDEA,在淘宝上花几块钱买个破解版,然后去https://www.oracle.com/java/technologies/downloads/#java8-windows下载JDK,然后参考http://www.51gjie.com/java/45.html配置JDK的环境变量,这样就可以在IDEA中选取JDK环境。完成后测试

package first_test;

public class test {
    public static void main(String[] args){
        System.out.println("hello world");
    }
}

run后结果:

hello world

表明已配置完成!!!

  1. 新建project

    image-20211220171727435

    image-20211220171803523

    image-20211220172054177

  2. 将 log4j.properties 文件拷贝到项目的 src 目录,便于我们在控制台输出日志

    image-20211220173117721

  3. 项目的根目录新建 lib 文件夹,将 jar 包拷贝到该目录下。

    image-20211220172749302

    一共6个jar包

  4. 将这些jar包做关联影射,File-> Project Structure->Libaries

    image-20211220173451737

    image-20211220173538818

    image-20211220173643039

    image-20211220173730592

    image-20211220174342302

  5. 在src文件夹中创建包以及需要用到的类

    首先,创建一个包com.bjsxt.api,然后在api里创建需要的类ZooKeeperTest,接下来,我们在类里进行定义

2.zk连接创建与关闭

package com.bjsxt.api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.After;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class ZooKeeperTest {
    //定义一个zk对象
    private ZooKeeper zooKeeper;
    //session的失效时间
    private static final int SESSION_TIMEOUT=30000;
    //定义一个Logger类对象
    public static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperTest.class);
    //定义一个监听器对象watcher
    private Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            LOGGER.info("process:"+event.getType());
        }
    };

    /**建立连接
     * 在后续的CRUD方法之前执行,LOGGER.info表示打印结果
     * @throws IOException
     */
    @Test
    public void connect() throws IOException {
        zooKeeper = new ZooKeeper("192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181",SESSION_TIMEOUT,watcher);
        LOGGER.info("zk:"+zooKeeper);
    }

    /**关闭连接对象
     * 在CRUD方法执行之后执行
     * @throws InterruptedException
     */
    @After
    public void close() throws InterruptedException {
        if(zooKeeper!=null){
            zooKeeper.close();
        }
    }

}

运行后结果:

2021-12-20 19:52:28,584 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2021-12-20 19:52:28,588 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=LAPTOP-G7CRBRST
2021-12-20 19:52:28,588 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_311
2021-12-20 19:52:28,588 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2021-12-20 19:52:28,588 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=D:\Java\jdk1.8.0_311\jre
2021-12-20 19:52:28,588 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit5-rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit-rt.jar;D:\java\jdk1.8.0_311\jre\lib\charsets.jar;D:\java\jdk1.8.0_311\jre\lib\deploy.jar;D:\java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8.0_311\jre\lib\ext\localedata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunec.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;D:\java\jdk1.8.0_311\jre\lib\javaws.jar;D:\java\jdk1.8.0_311\jre\lib\jce.jar;D:\java\jdk1.8.0_311\jre\lib\jfr.jar;D:\java\jdk1.8.0_311\jre\lib\jfxswt.jar;D:\java\jdk1.8.0_311\jre\lib\jsse.jar;D:\java\jdk1.8.0_311\jre\lib\management-agent.jar;D:\java\jdk1.8.0_311\jre\lib\plugin.jar;D:\java\jdk1.8.0_311\jre\lib\resources.jar;D:\java\jdk1.8.0_311\jre\lib\rt.jar;D:\IdeaProjects\baizhan\zookeeper_demo\out\production\zookeeper_demo;D:\IdeaProjects\baizhan\zookeeper_demo\lib\netty-3.7.0.Final.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\jline-0.9.94.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\log4j-1.2.16.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-api-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-log4j12-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\zookeeper-3.4.6.jar;C:\Users\admin\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar;C:\Users\admin\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar
2021-12-20 19:52:28,588 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=D:\Java\jdk1.8.0_311\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;D:\softwares\anaconda3;D:\softwares\anaconda3\Scripts;D:\softwares\anaconda3\Library\bin;D:\softwares\CUDA10.0\lib\x64;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\softwares\mysql5.6.39\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\softwares\anaconda3\envs\newtouch;D:\softwares\anaconda3\envs\newtouch\Scripts;D:\softwares\anaconda3\envs\newtouch\Library\bin;C:\Program Files\Git\cmd;D:\softwares\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.1\;D:\mysql\mysql56\bin;C:\windows;C:\windows\system32;C:\windows\system32\wbem;D:\softwares\CUDA10.0\bin;D:\softwares\CUDA10.0\libnvvp;D:\softwares\CUDA10.0\lib\x64;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\Git\cmd;D:\softwares\mysql5.6.39\bin;d:\softwares\anaconda3;d:\softwares\anaconda3\Library\mingw-w64\bin;d:\softwares\anaconda3\Library\usr\bin;d:\softwares\anaconda3\Library\bin;d:\softwares\anaconda3\Scripts;C:\Users\admin\anaconda3;C:\Users\admin\anaconda3\Library\mingw-w64\bin;C:\Users\admin\anaconda3\Library\usr\bin;C:\Users\admin\anaconda3\Library\bin;C:\Users\admin\anaconda3\Scripts;D:\python3.7\Scripts\;D:\python3.7\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;D:\办公\pycharm\PyCharm Community Edition 2020.1.1\bin;D:\software;C:\Users\admin\AppData\Roaming\npm;.
2021-12-20 19:52:28,589 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
2021-12-20 19:52:28,589 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2021-12-20 19:52:28,589 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Windows 10
2021-12-20 19:52:28,589 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2021-12-20 19:52:28,589 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=10.0
2021-12-20 19:52:28,589 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=admin
2021-12-20 19:52:28,589 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=C:\Users\admin
2021-12-20 19:52:28,589 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=D:\IdeaProjects\baizhan\zookeeper_demo
2021-12-20 19:52:28,590 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181 sessionTimeout=30000 watcher=com.bjsxt.api.ZooKeeperTest$1@42f30e0a
2021-12-20 19:52:29,381 [myid:] - INFO  [main:ZooKeeperTest@35] - zk:State:CONNECTING sessionid:0x0 local:null remoteserver:null lastZxid:0 xid:1 sent:0 recv:0 queuedpkts:0 pendingresp:0 queuedevents:0
2021-12-20 19:52:29,383 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.32/192.168.236.32:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-20 19:52:29,385 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.32/192.168.236.32:2181, initiating session
2021-12-20 19:52:29,400 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.32/192.168.236.32:2181, sessionid = 0x17dd4814b730000, negotiated timeout = 30000
2021-12-20 19:52:29,401 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@24] - process:None
2021-12-20 19:52:29,403 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x17dd4814b730000 closed
2021-12-20 19:52:29,403 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

3. 创建节点

    /**创建节点
     * create(final String path, byte data[], List<ACL> acl,
     *             CreateMode createMode)
     * path:节点的全路径名称
     * data[]:节点中保存的内容
     * acl:访问控制列表(可以参考《从Paxos到zookeeper》)
     * createMode:节点类型,封装了
     *          PERSISTENT:普通持久节点
     *          PERSISTENT_SEQUENTIAL:顺序持久节点
     *          EPHEMERAL:普通临时节点
     *          EPHEMERAL_SEQUENTIAL:顺序临时节点
     */
    @Test
    public void createNode(){
        String result = null;
        try {
            result = zooKeeper.create("/zkNode01", "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            LOGGER.info("create PERSISTENT node zkNode01 result:"+result);
            result = zooKeeper.create("/zkNode02","abc".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
            LOGGER.info("create EPHEMERAL node zkNode02 result:"+result);
            Thread.sleep(30000);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

运行结束后,我们在Xshell中连接zookeeper,可以发现:

[zk: localhost:2181(CONNECTED) 0] ls /
[zk02, zk01, zkNode01, zookeeper, zk03]

我们可以看到,创建的普通永久节点zkNode01存在,普通临时节点由于休眠30s,会话断开,临时节点消失。

4. 删除节点

    /**删除节点
     * delete(final String path, int version)
     *  path:被删除节点的全路径名
     *  version:对应节点的dataversion,要么和对应节点的dataversion值一样,要么写成-1(通常使用-1进行删除)
     */
    @Test
    public void deleteNode(){
        try {
            zooKeeper.delete("/zk03",-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail(); //抛出AssertionError异常
        }
    }
}

运行结束后,我们在Xshell中连接zookeeper,可以发现:

[zk: localhost:2181(CONNECTED) 1] ls /
[zk02, zk01, zkNode01, zookeeper]

zk03已经删除。但是,如果zk03下面还有子节点的话,是不允许执行删除操作的,即没有子节点的节点才可以被删除!

5. 获取数据和验证连接转移

    /**获取节点中的数据
     * 第一次获取某节点的数据(看从zk的哪个服务器中获取的数据)
     * xshell关闭对应zk节点
     * 第二次查看某节点的数据(看从zk节点是否发生改变)
     * 验证:客户端在连接中,如果对应的zk服务器出现故障,zk集群会将连接转移到其他服务器上,这个操作对客户端来说是透明的
     */
    @Test
    public void getNodeData(){
        try {
            byte[] data = zooKeeper.getData("/zkNode01", null, null);
            LOGGER.info("getData 1----:"+new String(data));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        try {
            Thread.sleep(25000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            byte[] data = zooKeeper.getData("/zkNode01", null, null);
            LOGGER.info("getData 2----:"+new String(data));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
    }

}

第一次连接成功后,我们可以看到它是从哪个服务器获取数据的,将这台服务器上的zookeeper关闭

[root@node3 bin]# zkServer.sh stop
JMX enabled by default
Using config: /opt/zookeeper-3.4.6/bin/../conf/zoo.cfg
Stopping zookeeper ... STOPPED

此时,可以看到连接转移到其他服务器上

2021-12-20 21:13:28,215 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2021-12-20 21:13:28,217 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=LAPTOP-G7CRBRST
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_311
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=D:\Java\jdk1.8.0_311\jre
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit5-rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit-rt.jar;D:\java\jdk1.8.0_311\jre\lib\charsets.jar;D:\java\jdk1.8.0_311\jre\lib\deploy.jar;D:\java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8.0_311\jre\lib\ext\localedata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunec.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;D:\java\jdk1.8.0_311\jre\lib\javaws.jar;D:\java\jdk1.8.0_311\jre\lib\jce.jar;D:\java\jdk1.8.0_311\jre\lib\jfr.jar;D:\java\jdk1.8.0_311\jre\lib\jfxswt.jar;D:\java\jdk1.8.0_311\jre\lib\jsse.jar;D:\java\jdk1.8.0_311\jre\lib\management-agent.jar;D:\java\jdk1.8.0_311\jre\lib\plugin.jar;D:\java\jdk1.8.0_311\jre\lib\resources.jar;D:\java\jdk1.8.0_311\jre\lib\rt.jar;D:\IdeaProjects\baizhan\zookeeper_demo\out\production\zookeeper_demo;D:\IdeaProjects\baizhan\zookeeper_demo\lib\netty-3.7.0.Final.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\jline-0.9.94.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\log4j-1.2.16.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-api-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-log4j12-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\zookeeper-3.4.6.jar;C:\Users\admin\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar;C:\Users\admin\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=D:\Java\jdk1.8.0_311\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;D:\softwares\anaconda3;D:\softwares\anaconda3\Scripts;D:\softwares\anaconda3\Library\bin;D:\softwares\CUDA10.0\lib\x64;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\softwares\mysql5.6.39\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\softwares\anaconda3\envs\newtouch;D:\softwares\anaconda3\envs\newtouch\Scripts;D:\softwares\anaconda3\envs\newtouch\Library\bin;C:\Program Files\Git\cmd;D:\softwares\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.1\;D:\mysql\mysql56\bin;C:\windows;C:\windows\system32;C:\windows\system32\wbem;D:\softwares\CUDA10.0\bin;D:\softwares\CUDA10.0\libnvvp;D:\softwares\CUDA10.0\lib\x64;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\Git\cmd;D:\softwares\mysql5.6.39\bin;d:\softwares\anaconda3;d:\softwares\anaconda3\Library\mingw-w64\bin;d:\softwares\anaconda3\Library\usr\bin;d:\softwares\anaconda3\Library\bin;d:\softwares\anaconda3\Scripts;C:\Users\admin\anaconda3;C:\Users\admin\anaconda3\Library\mingw-w64\bin;C:\Users\admin\anaconda3\Library\usr\bin;C:\Users\admin\anaconda3\Library\bin;C:\Users\admin\anaconda3\Scripts;D:\python3.7\Scripts\;D:\python3.7\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;D:\办公\pycharm\PyCharm Community Edition 2020.1.1\bin;D:\software;C:\Users\admin\AppData\Roaming\npm;.
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Windows 10
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=10.0
2021-12-20 21:13:28,218 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=admin
2021-12-20 21:13:28,219 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=C:\Users\admin
2021-12-20 21:13:28,219 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=D:\IdeaProjects\baizhan\zookeeper_demo
2021-12-20 21:13:28,219 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181 sessionTimeout=30000 watcher=com.bjsxt.api.ZooKeeperTest$1@24273305
2021-12-20 21:13:29,033 [myid:] - INFO  [main:ZooKeeperTest@36] - zk:State:CONNECTING sessionid:0x0 local:null remoteserver:null lastZxid:0 xid:1 sent:0 recv:0 queuedpkts:0 pendingresp:0 queuedevents:0
2021-12-20 21:13:29,035 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.33/192.168.236.33:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-20 21:13:29,036 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.33/192.168.236.33:2181, initiating session
2021-12-20 21:13:29,041 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.33/192.168.236.33:2181, sessionid = 0x27dd4814b6e0005, negotiated timeout = 30000
2021-12-20 21:13:29,042 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@25] - process:None
2021-12-20 21:13:29,045 [myid:] - INFO  [main:ZooKeeperTest@101] - getData 1----:hello
2021-12-20 21:13:43,031 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@1098] - Unable to read additional data from server sessionid 0x27dd4814b6e0005, likely server has closed socket, closing socket connection and attempting reconnect
2021-12-20 21:13:43,147 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@25] - process:None
2021-12-20 21:13:43,462 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.32/192.168.236.32:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-20 21:13:43,463 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.32/192.168.236.32:2181, initiating session
2021-12-20 21:13:43,464 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.32/192.168.236.32:2181, sessionid = 0x27dd4814b6e0005, negotiated timeout = 30000
2021-12-20 21:13:43,464 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@25] - process:None
2021-12-20 21:13:54,058 [myid:] - INFO  [main:ZooKeeperTest@113] - getData 2----:hello
2021-12-20 21:13:54,060 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x27dd4814b6e0005 closed
2021-12-20 21:13:54,060 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

6. 注册watcher监听和监听事件被触发

    /**watcher注册:在匿名内部类的匿名对象方式:new Watcher{}
     * 事件类型:
     *    NodeChildrenChanged:子节点发生变化
     *    NodeCreated:监听的节点被创建
     *    NodeDeleted:节点被删除
     *    NodeDataChanged:节点被修改
     * 得出的两个结论:
     *    1. Watcher监听是一次性的(只能被触发一次)
     *    2. 监听程序与方法主程序是线程异步的
     * 思考:如何实现监听被触发多次?
     *    事件触发后重新注册watcher监听
     */
    @Test
    public void getSetDataWatcher() {
        String result = null;
        //注册watcher监听
        try {
            System.out.println("get");
            byte[] data = zooKeeper.getData("/zkNode01", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    LOGGER.info("getSetDataWatcher watcher:{}", event.getType());
                    System.out.println("watcher work!");
                    getSetDataWatcher();  //事件触发后重新注册watcher监听
                }
            }, null);
            result = new String(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        LOGGER.info("getData result:{}", result);
        //触发监听事故
        try {
            System.out.println("set1");
            zooKeeper.setData("/zkNode01","setData_aaa".getBytes(),-1);
            System.out.println("set2");
            zooKeeper.setData("/zkNode01","setData_bbb".getBytes(),-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        System.out.println("show over!");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行程序后,我们可以看到:

2021-12-20 21:40:41,059 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2021-12-20 21:40:41,061 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=LAPTOP-G7CRBRST
2021-12-20 21:40:41,061 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_311
2021-12-20 21:40:41,061 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2021-12-20 21:40:41,061 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=D:\Java\jdk1.8.0_311\jre
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit5-rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit-rt.jar;D:\java\jdk1.8.0_311\jre\lib\charsets.jar;D:\java\jdk1.8.0_311\jre\lib\deploy.jar;D:\java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8.0_311\jre\lib\ext\localedata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunec.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;D:\java\jdk1.8.0_311\jre\lib\javaws.jar;D:\java\jdk1.8.0_311\jre\lib\jce.jar;D:\java\jdk1.8.0_311\jre\lib\jfr.jar;D:\java\jdk1.8.0_311\jre\lib\jfxswt.jar;D:\java\jdk1.8.0_311\jre\lib\jsse.jar;D:\java\jdk1.8.0_311\jre\lib\management-agent.jar;D:\java\jdk1.8.0_311\jre\lib\plugin.jar;D:\java\jdk1.8.0_311\jre\lib\resources.jar;D:\java\jdk1.8.0_311\jre\lib\rt.jar;D:\IdeaProjects\baizhan\zookeeper_demo\out\production\zookeeper_demo;D:\IdeaProjects\baizhan\zookeeper_demo\lib\netty-3.7.0.Final.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\jline-0.9.94.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\log4j-1.2.16.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-api-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-log4j12-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\zookeeper-3.4.6.jar;C:\Users\admin\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar;C:\Users\admin\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=D:\Java\jdk1.8.0_311\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;D:\softwares\anaconda3;D:\softwares\anaconda3\Scripts;D:\softwares\anaconda3\Library\bin;D:\softwares\CUDA10.0\lib\x64;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\softwares\mysql5.6.39\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\softwares\anaconda3\envs\newtouch;D:\softwares\anaconda3\envs\newtouch\Scripts;D:\softwares\anaconda3\envs\newtouch\Library\bin;C:\Program Files\Git\cmd;D:\softwares\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.1\;D:\mysql\mysql56\bin;C:\windows;C:\windows\system32;C:\windows\system32\wbem;D:\softwares\CUDA10.0\bin;D:\softwares\CUDA10.0\libnvvp;D:\softwares\CUDA10.0\lib\x64;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\Git\cmd;D:\softwares\mysql5.6.39\bin;d:\softwares\anaconda3;d:\softwares\anaconda3\Library\mingw-w64\bin;d:\softwares\anaconda3\Library\usr\bin;d:\softwares\anaconda3\Library\bin;d:\softwares\anaconda3\Scripts;C:\Users\admin\anaconda3;C:\Users\admin\anaconda3\Library\mingw-w64\bin;C:\Users\admin\anaconda3\Library\usr\bin;C:\Users\admin\anaconda3\Library\bin;C:\Users\admin\anaconda3\Scripts;D:\python3.7\Scripts\;D:\python3.7\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;D:\办公\pycharm\PyCharm Community Edition 2020.1.1\bin;D:\software;C:\Users\admin\AppData\Roaming\npm;.
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Windows 10
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=10.0
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=admin
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=C:\Users\admin
2021-12-20 21:40:41,062 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=D:\IdeaProjects\baizhan\zookeeper_demo
2021-12-20 21:40:41,063 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181 sessionTimeout=30000 watcher=com.bjsxt.api.ZooKeeperTest$1@24273305
2021-12-20 21:40:41,884 [myid:] - INFO  [main:ZooKeeperTest@38] - zk:State:CONNECTING sessionid:0x0 local:null remoteserver:null lastZxid:0 xid:1 sent:0 recv:0 queuedpkts:0 pendingresp:0 queuedevents:0
get
2021-12-20 21:40:41,886 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.32/192.168.236.32:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-20 21:40:41,887 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.32/192.168.236.32:2181, initiating session
2021-12-20 21:40:41,892 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.32/192.168.236.32:2181, sessionid = 0x17dd4814b730003, negotiated timeout = 30000
2021-12-20 21:40:41,893 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@25] - process:None
2021-12-20 21:40:41,896 [myid:] - INFO  [main:ZooKeeperTest@150] - getData result:hello
set1
set2
2021-12-20 21:40:41,900 [myid:] - INFO  [main-EventThread:ZooKeeperTest$2@141] - getSetDataWatcher watcher:NodeDataChanged
watcher work!
show over!
2021-12-20 21:41:01,921 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x17dd4814b730003 closed
2021-12-20 21:41:01,921 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

我可以得出的两个结论:

  1. Watcher监听是一次性的(只能被触发一次)
  2. 监听程序与方法主程序是线程异步的

7.判断节点是否存在和修改节点

	/**判断节点是否存在
     * exists(String path, boolean watch)
     *      1. path:节点路径
     *      2. watch为true表示使用zk连接对象上带的watcher,
     *         如果为false,则表示不使用连接对象上带的watcher
     * 如果节点不存在,返回null(抛出异常)
     * 如果节点存在,返回节点相关信息的Stat对象
     */
    @Test
    public void isExists(){
        Stat stat = null;
        try {
            stat = zooKeeper.exists("/zkNode01", false);//如果watch为True,则绑定定义的监听器对象watcher
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        Assert.assertNotNull(stat);  //判断对象是否为空,如果对象为空,会抛出异常
        LOGGER.info("node exists,stat version:{}",+stat.getVersion());
    }
    @Test
    public void setNodeData(){
        Stat stat = null;
        try {
        	//如果节点不存在则会抛出异常
            stat = zooKeeper.setData("/zkNode01", "helloworld".getBytes(), -1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        Assert.assertNotNull(stat); //判断对象是否为空,如果对象为空,会抛出异常
        LOGGER.info("setNodeData stat:{}",stat);
    }
}

运行结束后,结果为:

2021-12-21 11:03:31,797 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2021-12-21 11:03:31,799 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=LAPTOP-G7CRBRST
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_311
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=D:\Java\jdk1.8.0_311\jre
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit5-rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit-rt.jar;D:\java\jdk1.8.0_311\jre\lib\charsets.jar;D:\java\jdk1.8.0_311\jre\lib\deploy.jar;D:\java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8.0_311\jre\lib\ext\localedata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunec.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;D:\java\jdk1.8.0_311\jre\lib\javaws.jar;D:\java\jdk1.8.0_311\jre\lib\jce.jar;D:\java\jdk1.8.0_311\jre\lib\jfr.jar;D:\java\jdk1.8.0_311\jre\lib\jfxswt.jar;D:\java\jdk1.8.0_311\jre\lib\jsse.jar;D:\java\jdk1.8.0_311\jre\lib\management-agent.jar;D:\java\jdk1.8.0_311\jre\lib\plugin.jar;D:\java\jdk1.8.0_311\jre\lib\resources.jar;D:\java\jdk1.8.0_311\jre\lib\rt.jar;D:\IdeaProjects\baizhan\zookeeper_demo\out\production\zookeeper_demo;D:\IdeaProjects\baizhan\zookeeper_demo\lib\netty-3.7.0.Final.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\jline-0.9.94.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\log4j-1.2.16.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-api-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-log4j12-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\zookeeper-3.4.6.jar;C:\Users\admin\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar;C:\Users\admin\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=D:\Java\jdk1.8.0_311\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;D:\softwares\anaconda3;D:\softwares\anaconda3\Scripts;D:\softwares\anaconda3\Library\bin;D:\softwares\CUDA10.0\lib\x64;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\softwares\mysql5.6.39\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\softwares\anaconda3\envs\newtouch;D:\softwares\anaconda3\envs\newtouch\Scripts;D:\softwares\anaconda3\envs\newtouch\Library\bin;C:\Program Files\Git\cmd;D:\softwares\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.1\;D:\mysql\mysql56\bin;C:\windows;C:\windows\system32;C:\windows\system32\wbem;D:\softwares\CUDA10.0\bin;D:\softwares\CUDA10.0\libnvvp;D:\softwares\CUDA10.0\lib\x64;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\Git\cmd;D:\softwares\mysql5.6.39\bin;d:\softwares\anaconda3;d:\softwares\anaconda3\Library\mingw-w64\bin;d:\softwares\anaconda3\Library\usr\bin;d:\softwares\anaconda3\Library\bin;d:\softwares\anaconda3\Scripts;C:\Users\admin\anaconda3;C:\Users\admin\anaconda3\Library\mingw-w64\bin;C:\Users\admin\anaconda3\Library\usr\bin;C:\Users\admin\anaconda3\Library\bin;C:\Users\admin\anaconda3\Scripts;D:\python3.7\Scripts\;D:\python3.7\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;D:\办公\pycharm\PyCharm Community Edition 2020.1.1\bin;D:\software;C:\Users\admin\AppData\Roaming\npm;.
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Windows 10
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2021-12-21 11:03:31,800 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=10.0
2021-12-21 11:03:31,801 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=admin
2021-12-21 11:03:31,801 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=C:\Users\admin
2021-12-21 11:03:31,801 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=D:\IdeaProjects\baizhan\zookeeper_demo
2021-12-21 11:03:31,802 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181 sessionTimeout=30000 watcher=com.bjsxt.api.ZooKeeperTest$1@24273305
2021-12-21 11:03:32,655 [myid:] - INFO  [main:ZooKeeperTest@39] - zk:State:CONNECTING sessionid:0x0 local:null remoteserver:null lastZxid:0 xid:1 sent:0 recv:0 queuedpkts:0 pendingresp:0 queuedevents:0
2021-12-21 11:03:32,657 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.32/192.168.236.32:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-21 11:03:32,659 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.32/192.168.236.32:2181, initiating session
2021-12-21 11:03:32,665 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.32/192.168.236.32:2181, sessionid = 0x17dd56ba6d30002, negotiated timeout = 30000
2021-12-21 11:03:32,666 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@26] - process:None
2021-12-21 11:03:32,668 [myid:] - INFO  [main:ZooKeeperTest@194] - node exists,stat version:11
2021-12-21 11:03:32,670 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x17dd56ba6d30002 closed
2021-12-21 11:03:32,670 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

可以看出:节点存在。

2021-12-21 10:57:58,484 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2021-12-21 10:57:58,487 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=LAPTOP-G7CRBRST
2021-12-21 10:57:58,487 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_311
2021-12-21 10:57:58,487 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2021-12-21 10:57:58,487 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=D:\Java\jdk1.8.0_311\jre
2021-12-21 10:57:58,487 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit5-rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit-rt.jar;D:\java\jdk1.8.0_311\jre\lib\charsets.jar;D:\java\jdk1.8.0_311\jre\lib\deploy.jar;D:\java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8.0_311\jre\lib\ext\localedata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunec.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;D:\java\jdk1.8.0_311\jre\lib\javaws.jar;D:\java\jdk1.8.0_311\jre\lib\jce.jar;D:\java\jdk1.8.0_311\jre\lib\jfr.jar;D:\java\jdk1.8.0_311\jre\lib\jfxswt.jar;D:\java\jdk1.8.0_311\jre\lib\jsse.jar;D:\java\jdk1.8.0_311\jre\lib\management-agent.jar;D:\java\jdk1.8.0_311\jre\lib\plugin.jar;D:\java\jdk1.8.0_311\jre\lib\resources.jar;D:\java\jdk1.8.0_311\jre\lib\rt.jar;D:\IdeaProjects\baizhan\zookeeper_demo\out\production\zookeeper_demo;D:\IdeaProjects\baizhan\zookeeper_demo\lib\netty-3.7.0.Final.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\jline-0.9.94.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\log4j-1.2.16.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-api-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-log4j12-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\zookeeper-3.4.6.jar;C:\Users\admin\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar;C:\Users\admin\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar
2021-12-21 10:57:58,487 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=D:\Java\jdk1.8.0_311\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;D:\softwares\anaconda3;D:\softwares\anaconda3\Scripts;D:\softwares\anaconda3\Library\bin;D:\softwares\CUDA10.0\lib\x64;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\softwares\mysql5.6.39\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\softwares\anaconda3\envs\newtouch;D:\softwares\anaconda3\envs\newtouch\Scripts;D:\softwares\anaconda3\envs\newtouch\Library\bin;C:\Program Files\Git\cmd;D:\softwares\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.1\;D:\mysql\mysql56\bin;C:\windows;C:\windows\system32;C:\windows\system32\wbem;D:\softwares\CUDA10.0\bin;D:\softwares\CUDA10.0\libnvvp;D:\softwares\CUDA10.0\lib\x64;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\Git\cmd;D:\softwares\mysql5.6.39\bin;d:\softwares\anaconda3;d:\softwares\anaconda3\Library\mingw-w64\bin;d:\softwares\anaconda3\Library\usr\bin;d:\softwares\anaconda3\Library\bin;d:\softwares\anaconda3\Scripts;C:\Users\admin\anaconda3;C:\Users\admin\anaconda3\Library\mingw-w64\bin;C:\Users\admin\anaconda3\Library\usr\bin;C:\Users\admin\anaconda3\Library\bin;C:\Users\admin\anaconda3\Scripts;D:\python3.7\Scripts\;D:\python3.7\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;D:\办公\pycharm\PyCharm Community Edition 2020.1.1\bin;D:\software;C:\Users\admin\AppData\Roaming\npm;.
2021-12-21 10:57:58,488 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
2021-12-21 10:57:58,488 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2021-12-21 10:57:58,488 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Windows 10
2021-12-21 10:57:58,488 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2021-12-21 10:57:58,488 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=10.0
2021-12-21 10:57:58,488 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=admin
2021-12-21 10:57:58,488 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=C:\Users\admin
2021-12-21 10:57:58,488 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=D:\IdeaProjects\baizhan\zookeeper_demo
2021-12-21 10:57:58,489 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181 sessionTimeout=30000 watcher=com.bjsxt.api.ZooKeeperTest$1@24273305
2021-12-21 10:57:59,304 [myid:] - INFO  [main:ZooKeeperTest@39] - zk:State:CONNECTING sessionid:0x0 local:null remoteserver:null lastZxid:0 xid:1 sent:0 recv:0 queuedpkts:0 pendingresp:0 queuedevents:0
2021-12-21 10:57:59,307 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.32/192.168.236.32:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-21 10:57:59,308 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.32/192.168.236.32:2181, initiating session
2021-12-21 10:57:59,315 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.32/192.168.236.32:2181, sessionid = 0x17dd56ba6d30001, negotiated timeout = 30000
2021-12-21 10:57:59,316 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@26] - process:None
2021-12-21 10:57:59,321 [myid:] - INFO  [main:ZooKeeperTest@206] - setNodeData stat:21474836484,25769803785,1639953946008,1639964006397,11,0,0,0,10,0,21474836484

2021-12-21 10:57:59,323 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x17dd56ba6d30001 closed
2021-12-21 10:57:59,323 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

可以看出:节点已经被成功修改!

8.判断节点是否存在Watcher的使用

	/**判断节点是否存在Watcher的使用,这里使用定义好的监听对象
     *
     */
    @Test
    public void nodeExistsWatcher(){
        Stat stat = null;
        try {
            //watch=true表明使用定义好的监听对象
            stat = zooKeeper.exists("/zkNode01",true);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        Assert.assertNotNull(stat); //判断对象是否为空,如果对象为空,会抛出异常
        try {
            zooKeeper.delete("/zkNode01",-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
    }

    /** 判断节点是否存在Watcher的使用,这里使用自定义的监听对象
     * 
     */
    @Test
    public void nodeExistsUserDefWatcher(){
        Stat stat = null;
        try {
            stat = zooKeeper.exists("/zkNode01", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    LOGGER.info("nodeExistsUserDefWatcher watcher evevt_type:{}",event.getType());
                }
            });
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        Assert.assertNotNull(stat);

        try {
            zooKeeper.setData("/zkNode01","update_hello".getBytes(),-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        try {
            zooKeeper.delete("/zkNode01",-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
    }

运行nodeExistsWatcher结果为:

2021-12-21 11:23:45,798 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2021-12-21 11:23:45,801 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=LAPTOP-G7CRBRST
2021-12-21 11:23:45,801 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_311
2021-12-21 11:23:45,801 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2021-12-21 11:23:45,801 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=D:\Java\jdk1.8.0_311\jre
2021-12-21 11:23:45,801 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit5-rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit-rt.jar;D:\java\jdk1.8.0_311\jre\lib\charsets.jar;D:\java\jdk1.8.0_311\jre\lib\deploy.jar;D:\java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8.0_311\jre\lib\ext\localedata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunec.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;D:\java\jdk1.8.0_311\jre\lib\javaws.jar;D:\java\jdk1.8.0_311\jre\lib\jce.jar;D:\java\jdk1.8.0_311\jre\lib\jfr.jar;D:\java\jdk1.8.0_311\jre\lib\jfxswt.jar;D:\java\jdk1.8.0_311\jre\lib\jsse.jar;D:\java\jdk1.8.0_311\jre\lib\management-agent.jar;D:\java\jdk1.8.0_311\jre\lib\plugin.jar;D:\java\jdk1.8.0_311\jre\lib\resources.jar;D:\java\jdk1.8.0_311\jre\lib\rt.jar;D:\IdeaProjects\baizhan\zookeeper_demo\out\production\zookeeper_demo;D:\IdeaProjects\baizhan\zookeeper_demo\lib\netty-3.7.0.Final.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\jline-0.9.94.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\log4j-1.2.16.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-api-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-log4j12-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\zookeeper-3.4.6.jar;C:\Users\admin\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar;C:\Users\admin\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar
2021-12-21 11:23:45,801 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=D:\Java\jdk1.8.0_311\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;D:\softwares\anaconda3;D:\softwares\anaconda3\Scripts;D:\softwares\anaconda3\Library\bin;D:\softwares\CUDA10.0\lib\x64;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\softwares\mysql5.6.39\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\softwares\anaconda3\envs\newtouch;D:\softwares\anaconda3\envs\newtouch\Scripts;D:\softwares\anaconda3\envs\newtouch\Library\bin;C:\Program Files\Git\cmd;D:\softwares\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.1\;D:\mysql\mysql56\bin;C:\windows;C:\windows\system32;C:\windows\system32\wbem;D:\softwares\CUDA10.0\bin;D:\softwares\CUDA10.0\libnvvp;D:\softwares\CUDA10.0\lib\x64;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\Git\cmd;D:\softwares\mysql5.6.39\bin;d:\softwares\anaconda3;d:\softwares\anaconda3\Library\mingw-w64\bin;d:\softwares\anaconda3\Library\usr\bin;d:\softwares\anaconda3\Library\bin;d:\softwares\anaconda3\Scripts;C:\Users\admin\anaconda3;C:\Users\admin\anaconda3\Library\mingw-w64\bin;C:\Users\admin\anaconda3\Library\usr\bin;C:\Users\admin\anaconda3\Library\bin;C:\Users\admin\anaconda3\Scripts;D:\python3.7\Scripts\;D:\python3.7\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;D:\办公\pycharm\PyCharm Community Edition 2020.1.1\bin;D:\software;C:\Users\admin\AppData\Roaming\npm;.
2021-12-21 11:23:45,802 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
2021-12-21 11:23:45,802 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2021-12-21 11:23:45,802 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Windows 10
2021-12-21 11:23:45,802 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2021-12-21 11:23:45,802 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=10.0
2021-12-21 11:23:45,802 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=admin
2021-12-21 11:23:45,802 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=C:\Users\admin
2021-12-21 11:23:45,802 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=D:\IdeaProjects\baizhan\zookeeper_demo
2021-12-21 11:23:45,803 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181 sessionTimeout=30000 watcher=com.bjsxt.api.ZooKeeperTest$1@24273305
2021-12-21 11:23:46,635 [myid:] - INFO  [main:ZooKeeperTest@39] - zk:State:CONNECTING sessionid:0x0 local:null remoteserver:null lastZxid:0 xid:1 sent:0 recv:0 queuedpkts:0 pendingresp:0 queuedevents:0
2021-12-21 11:23:46,637 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.32/192.168.236.32:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-21 11:23:46,638 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.32/192.168.236.32:2181, initiating session
2021-12-21 11:23:46,645 [myid:] - INFO  [main-SendThread(192.168.236.32:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.32/192.168.236.32:2181, sessionid = 0x17dd56ba6d30003, negotiated timeout = 30000
2021-12-21 11:23:46,646 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@26] - process:None
2021-12-21 11:23:46,651 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@26] - process:NodeDeleted
2021-12-21 11:23:46,654 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x17dd56ba6d30003 closed
2021-12-21 11:23:46,654 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

发现:删除节点操作被监听。

然后,重新创建/zkNode01,再运行nodeExistsUserDefWatcher,结果为:

2021-12-21 11:30:00,716 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2021-12-21 11:30:00,719 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=LAPTOP-G7CRBRST
2021-12-21 11:30:00,719 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_311
2021-12-21 11:30:00,719 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2021-12-21 11:30:00,719 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=D:\Java\jdk1.8.0_311\jre
2021-12-21 11:30:00,719 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit5-rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit-rt.jar;D:\java\jdk1.8.0_311\jre\lib\charsets.jar;D:\java\jdk1.8.0_311\jre\lib\deploy.jar;D:\java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8.0_311\jre\lib\ext\localedata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunec.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;D:\java\jdk1.8.0_311\jre\lib\javaws.jar;D:\java\jdk1.8.0_311\jre\lib\jce.jar;D:\java\jdk1.8.0_311\jre\lib\jfr.jar;D:\java\jdk1.8.0_311\jre\lib\jfxswt.jar;D:\java\jdk1.8.0_311\jre\lib\jsse.jar;D:\java\jdk1.8.0_311\jre\lib\management-agent.jar;D:\java\jdk1.8.0_311\jre\lib\plugin.jar;D:\java\jdk1.8.0_311\jre\lib\resources.jar;D:\java\jdk1.8.0_311\jre\lib\rt.jar;D:\IdeaProjects\baizhan\zookeeper_demo\out\production\zookeeper_demo;D:\IdeaProjects\baizhan\zookeeper_demo\lib\netty-3.7.0.Final.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\jline-0.9.94.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\log4j-1.2.16.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-api-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-log4j12-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\zookeeper-3.4.6.jar;C:\Users\admin\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar;C:\Users\admin\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar
2021-12-21 11:30:00,719 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=D:\Java\jdk1.8.0_311\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;D:\softwares\anaconda3;D:\softwares\anaconda3\Scripts;D:\softwares\anaconda3\Library\bin;D:\softwares\CUDA10.0\lib\x64;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\softwares\mysql5.6.39\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\softwares\anaconda3\envs\newtouch;D:\softwares\anaconda3\envs\newtouch\Scripts;D:\softwares\anaconda3\envs\newtouch\Library\bin;C:\Program Files\Git\cmd;D:\softwares\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.1\;D:\mysql\mysql56\bin;C:\windows;C:\windows\system32;C:\windows\system32\wbem;D:\softwares\CUDA10.0\bin;D:\softwares\CUDA10.0\libnvvp;D:\softwares\CUDA10.0\lib\x64;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\Git\cmd;D:\softwares\mysql5.6.39\bin;d:\softwares\anaconda3;d:\softwares\anaconda3\Library\mingw-w64\bin;d:\softwares\anaconda3\Library\usr\bin;d:\softwares\anaconda3\Library\bin;d:\softwares\anaconda3\Scripts;C:\Users\admin\anaconda3;C:\Users\admin\anaconda3\Library\mingw-w64\bin;C:\Users\admin\anaconda3\Library\usr\bin;C:\Users\admin\anaconda3\Library\bin;C:\Users\admin\anaconda3\Scripts;D:\python3.7\Scripts\;D:\python3.7\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;D:\办公\pycharm\PyCharm Community Edition 2020.1.1\bin;D:\software;C:\Users\admin\AppData\Roaming\npm;.
2021-12-21 11:30:00,720 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
2021-12-21 11:30:00,720 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2021-12-21 11:30:00,720 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Windows 10
2021-12-21 11:30:00,720 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2021-12-21 11:30:00,720 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=10.0
2021-12-21 11:30:00,720 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=admin
2021-12-21 11:30:00,720 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=C:\Users\admin
2021-12-21 11:30:00,721 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=D:\IdeaProjects\baizhan\zookeeper_demo
2021-12-21 11:30:00,722 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181 sessionTimeout=30000 watcher=com.bjsxt.api.ZooKeeperTest$1@24273305
2021-12-21 11:30:01,577 [myid:] - INFO  [main:ZooKeeperTest@39] - zk:State:CONNECTING sessionid:0x0 local:null remoteserver:null lastZxid:0 xid:1 sent:0 recv:0 queuedpkts:0 pendingresp:0 queuedevents:0
2021-12-21 11:30:01,580 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.33/192.168.236.33:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-21 11:30:01,581 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.33/192.168.236.33:2181, initiating session
2021-12-21 11:30:01,586 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.33/192.168.236.33:2181, sessionid = 0x27dd573cc600001, negotiated timeout = 30000
2021-12-21 11:30:01,587 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@26] - process:None
2021-12-21 11:30:01,596 [myid:] - INFO  [main-EventThread:ZooKeeperTest$3@242] - nodeExistsUserDefWatcher watcher evevt_type:NodeDataChanged
2021-12-21 11:30:01,601 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x27dd573cc600001 closed
2021-12-21 11:30:01,601 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

发现:修改触发了watcher机制,删除并没有触发。watcher机制只能被触发一次,由于setData先触发了,delete就没有触发。

9.子节点查询

/**获取子节点名称查询
     * 获取子节点内容查询,将子节点内容添加到内容集合中
     */
    @Test
    public void getChildNodes(){
        List<String> childContentList = new ArrayList<>();
        try {
            List<String> childrens = zooKeeper.getChildren("/zk02", true);
            for(String children:childrens){
                System.out.println(children); //打印节点名称
                byte[] data = zooKeeper.getData("/zk02/" + children, null, null); //path:子节点路径
                childContentList.add(new String(data)); //将字节数组转化为String并添加到childContentList列表中
            }
            for (String childContent:childContentList){
                System.out.println(childContent);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
    }

运行结果为:

2021-12-21 11:49:27,204 [myid:] - INFO  [main:Environment@100] - Client environment:zookeeper.version=3.4.6-1569965, built on 02/20/2014 09:09 GMT
2021-12-21 11:49:27,207 [myid:] - INFO  [main:Environment@100] - Client environment:host.name=LAPTOP-G7CRBRST
2021-12-21 11:49:27,208 [myid:] - INFO  [main:Environment@100] - Client environment:java.version=1.8.0_311
2021-12-21 11:49:27,208 [myid:] - INFO  [main:Environment@100] - Client environment:java.vendor=Oracle Corporation
2021-12-21 11:49:27,208 [myid:] - INFO  [main:Environment@100] - Client environment:java.home=D:\Java\jdk1.8.0_311\jre
2021-12-21 11:49:27,208 [myid:] - INFO  [main:Environment@100] - Client environment:java.class.path=D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit5-rt.jar;D:\softwares\IntelliJ IDEA 2021.3\plugins\junit\lib\junit-rt.jar;D:\java\jdk1.8.0_311\jre\lib\charsets.jar;D:\java\jdk1.8.0_311\jre\lib\deploy.jar;D:\java\jdk1.8.0_311\jre\lib\ext\access-bridge-64.jar;D:\java\jdk1.8.0_311\jre\lib\ext\cldrdata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\dnsns.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jaccess.jar;D:\java\jdk1.8.0_311\jre\lib\ext\jfxrt.jar;D:\java\jdk1.8.0_311\jre\lib\ext\localedata.jar;D:\java\jdk1.8.0_311\jre\lib\ext\nashorn.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunec.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunjce_provider.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunmscapi.jar;D:\java\jdk1.8.0_311\jre\lib\ext\sunpkcs11.jar;D:\java\jdk1.8.0_311\jre\lib\ext\zipfs.jar;D:\java\jdk1.8.0_311\jre\lib\javaws.jar;D:\java\jdk1.8.0_311\jre\lib\jce.jar;D:\java\jdk1.8.0_311\jre\lib\jfr.jar;D:\java\jdk1.8.0_311\jre\lib\jfxswt.jar;D:\java\jdk1.8.0_311\jre\lib\jsse.jar;D:\java\jdk1.8.0_311\jre\lib\management-agent.jar;D:\java\jdk1.8.0_311\jre\lib\plugin.jar;D:\java\jdk1.8.0_311\jre\lib\resources.jar;D:\java\jdk1.8.0_311\jre\lib\rt.jar;D:\IdeaProjects\baizhan\zookeeper_demo\out\production\zookeeper_demo;D:\IdeaProjects\baizhan\zookeeper_demo\lib\netty-3.7.0.Final.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\jline-0.9.94.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\log4j-1.2.16.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-api-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\slf4j-log4j12-1.6.1.jar;D:\IdeaProjects\baizhan\zookeeper_demo\lib\zookeeper-3.4.6.jar;C:\Users\admin\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar;C:\Users\admin\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;D:\softwares\IntelliJ IDEA 2021.3\lib\idea_rt.jar
2021-12-21 11:49:27,208 [myid:] - INFO  [main:Environment@100] - Client environment:java.library.path=D:\Java\jdk1.8.0_311\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin;C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\libnvvp;D:\softwares\anaconda3;D:\softwares\anaconda3\Scripts;D:\softwares\anaconda3\Library\bin;D:\softwares\CUDA10.0\lib\x64;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\softwares\mysql5.6.39\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;D:\softwares\anaconda3\envs\newtouch;D:\softwares\anaconda3\envs\newtouch\Scripts;D:\softwares\anaconda3\envs\newtouch\Library\bin;C:\Program Files\Git\cmd;D:\softwares\nodejs\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\NVIDIA Corporation\Nsight Compute 2019.1\;D:\mysql\mysql56\bin;C:\windows;C:\windows\system32;C:\windows\system32\wbem;D:\softwares\CUDA10.0\bin;D:\softwares\CUDA10.0\libnvvp;D:\softwares\CUDA10.0\lib\x64;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\Program Files\NVIDIA Corporation\NVIDIA NvDLISR;C:\Program Files\MySQL\MySQL Server 8.0\bin;D:\MySQL\MySQL Server 5.5\bin;D:\softwares\anaconda3\graphviz\bin;D:\Git\cmd;D:\softwares\mysql5.6.39\bin;d:\softwares\anaconda3;d:\softwares\anaconda3\Library\mingw-w64\bin;d:\softwares\anaconda3\Library\usr\bin;d:\softwares\anaconda3\Library\bin;d:\softwares\anaconda3\Scripts;C:\Users\admin\anaconda3;C:\Users\admin\anaconda3\Library\mingw-w64\bin;C:\Users\admin\anaconda3\Library\usr\bin;C:\Users\admin\anaconda3\Library\bin;C:\Users\admin\anaconda3\Scripts;D:\python3.7\Scripts\;D:\python3.7\;C:\Users\admin\AppData\Local\Microsoft\WindowsApps;D:\办公\pycharm\PyCharm Community Edition 2020.1.1\bin;D:\software;C:\Users\admin\AppData\Roaming\npm;.
2021-12-21 11:49:27,208 [myid:] - INFO  [main:Environment@100] - Client environment:java.io.tmpdir=C:\Users\admin\AppData\Local\Temp\
2021-12-21 11:49:27,209 [myid:] - INFO  [main:Environment@100] - Client environment:java.compiler=<NA>
2021-12-21 11:49:27,209 [myid:] - INFO  [main:Environment@100] - Client environment:os.name=Windows 10
2021-12-21 11:49:27,209 [myid:] - INFO  [main:Environment@100] - Client environment:os.arch=amd64
2021-12-21 11:49:27,209 [myid:] - INFO  [main:Environment@100] - Client environment:os.version=10.0
2021-12-21 11:49:27,209 [myid:] - INFO  [main:Environment@100] - Client environment:user.name=admin
2021-12-21 11:49:27,209 [myid:] - INFO  [main:Environment@100] - Client environment:user.home=C:\Users\admin
2021-12-21 11:49:27,209 [myid:] - INFO  [main:Environment@100] - Client environment:user.dir=D:\IdeaProjects\baizhan\zookeeper_demo
2021-12-21 11:49:27,210 [myid:] - INFO  [main:ZooKeeper@438] - Initiating client connection, connectString=192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181 sessionTimeout=30000 watcher=com.bjsxt.api.ZooKeeperTest$1@24273305
2021-12-21 11:49:28,049 [myid:] - INFO  [main:ZooKeeperTest@41] - zk:State:CONNECTING sessionid:0x0 local:null remoteserver:null lastZxid:0 xid:1 sent:0 recv:0 queuedpkts:0 pendingresp:0 queuedevents:0
2021-12-21 11:49:28,051 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@975] - Opening socket connection to server 192.168.236.33/192.168.236.33:2181. Will not attempt to authenticate using SASL (unknown error)
2021-12-21 11:49:28,052 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@852] - Socket connection established to 192.168.236.33/192.168.236.33:2181, initiating session
2021-12-21 11:49:28,057 [myid:] - INFO  [main-SendThread(192.168.236.33:2181):ClientCnxn$SendThread@1235] - Session establishment complete on server 192.168.236.33/192.168.236.33:2181, sessionid = 0x27dd573cc600002, negotiated timeout = 30000
2021-12-21 11:49:28,058 [myid:] - INFO  [main-EventThread:ZooKeeperTest$1@28] - process:None
node30000000002
node1
helloworld
hello
2021-12-21 11:49:28,068 [myid:] - INFO  [main:ZooKeeper@684] - Session: 0x27dd573cc600002 closed
2021-12-21 11:49:28,068 [myid:] - INFO  [main-EventThread:ClientCnxn$EventThread@512] - EventThread shut down

10. 全部程序

package com.bjsxt.api;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class ZooKeeperTest {
    //定义一个zk对象
    private ZooKeeper zooKeeper;
    //session的失效时间
    private static final int SESSION_TIMEOUT = 30000;
    //定义一个Logger类对象
    public static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperTest.class);
    //定义一个监听器对象watcher
    private Watcher watcher = new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            LOGGER.info("process:" + event.getType());
        }
    };

    /**
     * 建立连接
     * 在后续的CRUD方法之前执行,LOGGER.info表示打印结果
     *
     * @throws IOException
     */
    @Before
    public void connect() throws IOException {
        zooKeeper = new ZooKeeper("192.168.236.32:2181,192.168.236.33:2181,192.168.236.34:2181", SESSION_TIMEOUT, watcher);
        LOGGER.info("zk:" + zooKeeper);
    }

    /**
     * 关闭连接对象
     * 在CRUD方法执行之后执行
     *
     * @throws InterruptedException
     */
    @After
    public void close() throws InterruptedException {
        if (zooKeeper != null) {
            zooKeeper.close();
        }
    }

    /**
     * 创建节点
     * create(final String path, byte data[], List<ACL> acl,
     * CreateMode createMode)
     * path:节点的全路径名称
     * data[]:节点中保存的内容
     * acl:访问控制列表(可以参考《从Paxos到zookeeper》)
     * createMode:节点类型,封装了
     * PERSISTENT:普通持久节点
     * PERSISTENT_SEQUENTIAL:顺序持久节点
     * EPHEMERAL:普通临时节点
     * EPHEMERAL_SEQUENTIAL:顺序临时节点
     */
    @Test
    public void createNode() {
        String result = null;
        try {
            result = zooKeeper.create("/zkNode01", "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            LOGGER.info("create PERSISTENT node zkNode01 result:" + result);
            result = zooKeeper.create("/zkNode02", "abc".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            LOGGER.info("create EPHEMERAL node zkNode02 result:" + result);
            Thread.sleep(30000);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**删除节点
     * delete(final String path, int version)
     *  path:被删除节点的全路径名
     *  version:对应节点的dataversion,要么和对应节点的dataversion值一样,要么写成-1(通常使用-1进行删除)
     */
    @Test
    public void deleteNode(){
        try {
            zooKeeper.delete("/zk03",-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail(); //抛出AssertionError异常
        }
    }

    /**
     * 获取节点中的数据
     * 第一次获取某节点的数据(看从zk的哪个服务器中获取的数据)
     * xshell关闭对应zk节点
     * 第二次查看某节点的数据(看从zk节点是否发生改变)
     */
    @Test
    public void getNodeData() {
        try {
            byte[] data = zooKeeper.getData("/zkNode01", null, null);
            LOGGER.info("getData 1----:" + new String(data));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        try {
            Thread.sleep(25000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            byte[] data = zooKeeper.getData("/zkNode01", null, null);
            LOGGER.info("getData 2----:" + new String(data));
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
    }

    /**watcher注册:在匿名内部类的匿名对象方式:new Watcher{}
     * 事件类型:
     *    NodeChildrenChanged:子节点发生变化
     *    NodeCreated:监听的节点被创建
     *    NodeDeleted:节点被删除
     *    NodeDataChanged:节点被修改
     * 得出的两个结论:
     *    1. Watcher监听是一次性的(只能被触发一次)
     *    2. 监听程序与方法主程序是线程异步的
     * 思考:如何实现监听被触发多次?
     *    事件触发后重新注册watcher监听
     */
    @Test
    public void getSetDataWatcher() {
        String result = null;
        //注册watcher监听
        try {
            System.out.println("get");
            byte[] data = zooKeeper.getData("/zkNode01", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    LOGGER.info("getSetDataWatcher watcher:{}", event.getType());
                    System.out.println("watcher work!");
                    getSetDataWatcher();  //事件触发后重新注册watcher监听
                }
            }, null);
            result = new String(data);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        LOGGER.info("getData result:{}", result);
        //触发监听事故
        try {
            System.out.println("set1");
            zooKeeper.setData("/zkNode01","setData_aaa".getBytes(),-1);
            System.out.println("set2");
            zooKeeper.setData("/zkNode01","setData_bbb".getBytes(),-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        System.out.println("show over!");
        try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**判断节点是否存在
     * exists(String path, boolean watch)
     *      1. path:节点路径
     *      2. watch为true表示使用zk连接对象上带的watcher,
     *         如果为false,则表示不使用连接对象上带的watcher
     * 如果节点不存在,返回null(抛出异常)
     * 如果节点存在,返回节点相关信息的Stat对象
     */
    @Test
    public void isExists(){
        Stat stat = null;
        try {
            stat = zooKeeper.exists("/zkNode01", false);//如果watch为True,则绑定定义的监听器对象watcher
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        Assert.assertNotNull(stat);  //判断对象是否为空,如果对象为空,会抛出异常
        LOGGER.info("node exists,stat version:{}",+stat.getVersion());
    }
    @Test
    public void setNodeData(){
        Stat stat = null;
        try {
            //如果节点不存在则会抛出异常
            stat = zooKeeper.setData("/zkNode01", "helloworld".getBytes(), -1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        Assert.assertNotNull(stat); //判断对象是否为空,如果对象为空,会抛出异常
        LOGGER.info("setNodeData stat:{}",stat);
    }

    /**判断节点是否存在Watcher的使用,这里使用定义好的监听对象
     *
     */
    @Test
    public void nodeExistsWatcher(){
        Stat stat = null;
        try {
            //watch=true表明使用定义好的监听对象
            stat = zooKeeper.exists("/zkNode01",true);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        Assert.assertNotNull(stat); //判断对象是否为空,如果对象为空,会抛出异常
        try {
            zooKeeper.delete("/zkNode01",-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
    }

    /** 判断节点是否存在Watcher的使用,这里使用自定义的监听对象
     *
     */
    @Test
    public void nodeExistsUserDefWatcher(){
        Stat stat = null;
        try {
            stat = zooKeeper.exists("/zkNode01", new Watcher() {
                @Override
                public void process(WatchedEvent event) {
                    LOGGER.info("nodeExistsUserDefWatcher watcher evevt_type:{}",event.getType());
                }
            });
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        Assert.assertNotNull(stat);

        try {
            zooKeeper.setData("/zkNode01","update_hello".getBytes(),-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
        try {
            zooKeeper.delete("/zkNode01",-1);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
    }

    /**获取子节点名称查询
     * 获取子节点内容查询,将子节点内容添加到内容集合中
     */
    @Test
    public void getChildNodes(){
        List<String> childContentList = new ArrayList<>();
        try {
            List<String> childrens = zooKeeper.getChildren("/zk02", true);
            for(String children:childrens){
                System.out.println(children); //打印节点名称
                byte[] data = zooKeeper.getData("/zk02/" + children, null, null); //path:子节点路径
                childContentList.add(new String(data)); //将字节数组转化为String并添加到childContentList列表中
            }
            for (String childContent:childContentList){
                System.out.println(childContent);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            Assert.fail();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值