本文共 2377 字,大约阅读时间需要 7 分钟。
org.apache.zookeeper.Zookeeper
org.apache.zookeeper.Watcher
Watcher接口表示一个标准的事件处理器,其定义了事件通知相关的逻辑,包含KeeperState和EventType两个枚举类,分别代表了通知状态和事件类型,同时定义了事件的回调方法:process(WatchedEvent event)。 process方法是Watcher接口中的一个回调方法,当Zookeeper向客户端发送一个Watcher事件通知时,客户端就会对相应的process方法进行回调,从而实现对事件的处理。
1. 搭建zookeeper2020项目
添加如下依赖:
org.apache.zookeeper zookeeper 3.4.9
3. 启动类
创建com.antherd.Application
package com.antherd;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooKeeper;public class Application { public static void main(String[] args) throws Exception{ // 构造java zk客户端 ZooKeeper zk = new ZooKeeper( "ip1:2181,ip2:2181,ip3:2181", 30000, new Watcher() { // 多个ip使用‘,’隔开,注意‘,’后面不能添加空格 // 事件通知的回调方法 @Override public void process(WatchedEvent event) { System.out.println("Event State: " + event.getState()); System.out.println("Event Type: " + event.getType()); System.out.println("Event Path: " + event.getPath()); } }); zk.close(); }}
运行main方法,发现控制台展示了Connect事件信息
zk.create("/myGirls", "性感的".getBytes(StandardCharsets.UTF_8), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
运行main方法,在Zookeeper服务端查看发现节点创建成功
// 创建一个目录节点zk.create("/testRootPath", "testRootData".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);// 创建一个子目录节点zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);// 取出子目录节点列表// 取出节点数据System.out.println(new String(zk.getData("/testRootPath", false, null)));// 取出子目录节点列表,并且监听/testRootPath变化事件,多次修改只会产生一次事件System.out.println(zk.getChildren("/testRootPath", true));// 修改子目录节点数据zk.setData("/testRootPath/testChildPathOne", "modifyChildDataOne".getBytes(), -1);System.out.println("目录节点状态:[" + zk.exists("/testRootPath", true) + "]");// 创建另外一个子目录节点zk.create("/testRootPath/testChildPathTwo", "testChildDataTwo".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println(new String(zk.getData("/testRootPath/getChildPathTwo", true, null)));// 删除子目录节点zk.delete("/testRootPath/testChildPathOne", -1);zk.delete("/testRootPath/testChildPathTwo", -1);// 删除父目录节点zk.delete("/testRootPath", -1);
转载地址:http://ldiz.baihongyu.com/