一、监听节点
先看看怎么获取子节点,启动zookeeper服务集群。编写并运行如下测试案例。
public class ZKClient {
ZooKeeper client;
@Before
public void init() throws IOException {
// 注意逗号后不要加空格,严格按照格式,在下面写自己对应得zookeeper服务集群得ip
String connectString="192.168.106.43:2182,192.168.106.44:2182,192.168.106.45:2182";
// String connectString="192.168.106.43,192.168.106.44,192.168.106.45";
int sessionTimeout = 20000;
client = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
}
@Test
public void grtChild() throws InterruptedException, KeeperException {
// 参数true表示开启子节点的监听
List<String> children = client.getChildren("/", true);
for (String child: children) {
System.out.println(child);
}
}
}
上面并不能实时监听节点的变化,即使我们在使用getChildren
是开启了子节点的监听。这是因为两个原因:第一,程序执行完一次监听后就退出了。第二,监听器注册一次只能够监听一次(参考:Zookeeper入门到精通05——Zookeeper客户端命令行操作,小节:监听器原理)。如何才能够实时监听子节点,并且一有变化就输出呢?很简单,把上面的代码稍微修改下即可。
public class ZKClient {
ZooKeeper client;
@Before
public void init() throws IOException {
// 注意逗号后不要加空格,严格按照格式,在下面写自己对应得zookeeper服务集群得ip
String connectString="192.168.106.43:2182,192.168.106.44:2182,192.168.106.45:2182";
// String connectString="192.168.106.43,192.168.106.44,192.168.106.45";
int sessionTimeout = 20000;
client = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
List<String> children = null;
try {
// 参数true表示开启子节点的监听
children = client.getChildren("/", true);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (String child: children) {
System.out.println(child);
}
}
});
}
}
@Test
public void grtChild() throws InterruptedException, KeeperException {
List<String> children = client.getChildren("/", true);
for (String child: children) {
System.out.println(child);
}
// 延时阻塞,防止程序退出
Thread.sleep(Long.MAX_VALUE);
}
二、判断节点是否存在
public class ZKClient {
ZooKeeper client;
@Before
![img](https://img-blog.csdnimg.cn/img_convert/b2b682c283e360c380b5151da4cfcc4e.png)
![img](https://img-blog.csdnimg.cn/img_convert/bfcb200c72865b48eff465bd7b4b6f1a.png)
![img](https://img-blog.csdnimg.cn/img_convert/d280228447c1fbd60a3efa68620ad581.png)
**既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上大数据知识点,真正体系化!**
**由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**
笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**