Watch是ZooKeeper中非常重要的一个机制,它可以监控ZooKeeper中节点的变化情况,告知客户端。下面,我们以代码为例来分析Watch在ZooKeeper中是如何实现的。ZooKeeper中一共由三种方法可以实现Watch,分别为getData、exists和getChildren,今天我们先来看下getChildren()方法:
3、getChildren
import java.io.IOException;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
public class TestZooKeeperWatcher {
public static void main(String[] args) {
ZooKeeper zk = null;
try {
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("开始连接ZooKeeper...");
// 创建与ZooKeeper服务器的连接zk
String address = "192.168.1.226:2181";
int sessionTimeout = 3000;
zk = new ZooKeeper(address, sessionTimeout, new Watcher() {
// 监控所有被触发的事件
public void process(WatchedEvent event) {
if (event.getType() == null || "".equals(event.getType())) {
return;
}
System.out.println("已经触发了" + event.getType() + "事件!");
}
});
System.out.println("ZooKeeper连接创建成功!");
Thread.currentThread().sleep(1000l);
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("...");
// 创建根目录节点
// 路径为/tmp_root_path
// 节点内容为字符串"我是根目录/tmp_root_path"
// 创建模式为CreateMode.PERSISTENT
System.out.println("开始创建根目录节点/tmp_root_path...");
zk.create("/tmp_root_path", "我是根目录/tmp_root_path".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("根目录节点/tmp_root_path创建成功!");
Thread.currentThread().sleep(1000l);
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("...");
// 获取子目录节点列表
System.out.println("开始获取根目录/tmp_root_path节点的子目录节点列...");
System.out.println(zk.getChildren("/tmp_root_path", true));
System.out.println("根目录/tmp_root_path节点的子目录节点列获取成功!");
Thread.currentThread().sleep(1000l);
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("...");
// 创建第一个子目录节点
// 路径为/tmp_root_path/childPath1
// 节点内容为字符串"我是第一个子目录/tmp_root_path/childPath1"
// 创建模式为CreateMode.PERSISTENT
System.out.println("开始创建第一个子目录节点/tmp_root_path/childPath1...");
zk.create("/tmp_root_path/childPath1",
"我是第一个子目录/tmp_root_path/childPath1".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("第一个子目录节点/tmp_root_path/childPath1创建成功!");
Thread.currentThread().sleep(1000l);
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("...