Java实现ZooKeeper的zNode监控

时间:2021-05-20

上一篇文章已经完成了ZooKeeper的基本搭建和使用的介绍,现在开始用代码说话。参考 https://zookeeper.apache.org/doc/current/javaExample.html ,但对场景和代码都做了简化,只实现基本的Watcher功能。

1 场景设计

目的是体验ZooKeeper的Watcher功能。程序监控ZooKeeper的/watcher节点数据变化,当创建或修改数据时,控制台打印当前的数据内容和版本号;当/watcher被删除时,程序退出。

/watcher的创建、修改和删除操作,使用控制台或zkui操作。

2 搭建Maven项目

代码相对比较简单,就不用SpringBoot这个大杀器了,使用一个普通的Maven项目即可。

ZooKeeper客户端使用官方提供的Java库,org.apache.zookeeper: zookeeper: 3.5.5。日志框架使用习惯的slf4j+log4j2,ZooKeeper缺省使用的是log4j V1,因此在引入的时候需要excludes。另外,使用了lombok来简化一些代码。

以下是pom.xml的内容

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://xn.java:1254) [zookeeper-3.5.5.jar:3.5.5]Caused by: java.nio.channels.NotYetConnectedException at sun.nio.ch.SocketChannelImpl.shutdownInput(SocketChannelImpl.java:917) ~[?:?] at sun.nio.ch.SocketAdaptor.shutdownInput(SocketAdaptor.java:398) ~[?:?] ... 4 moreNotYetConnectedException的字面意思是连接还没有创建好,网络搜索了一下,建立连接需要一些时间,创建zk对象后马上调用exists命令,这时候连接还没有创建好,就会抛异常。ZooKeeper在连接建立成功之后,会发送一个WatchedEvent事件,我们可以利用这个事件完成建立连接的过程。修改后的代码如下,顺便添加了slf4j-ext中的Profiler,用于记录所消耗的时间。public class ZooKeeperWatcher implements Watcher { /** 等待连接建立成功的信号 */ private CountDownLatch connectedSemaphore = new CountDownLatch(1); /** ZooKeeper的客户端连接 */ ZooKeeper zk; public ZooKeeperWatcher(String hostPort, String zNode) throws KeeperException, IOException { Profiler profiler = new Profiler("连接到ZooKeeper"); profiler.start("开始链接"); zk = new ZooKeeper(hostPort, 3000, this); try { profiler.start("等待连接成功的Event"); connectedSemaphore.await(); Stat exists = zk.exists(zNode, true); if(exists == null){ log.info(“{} 不存在”, zNode) } } catch (InterruptedException e) { log.error("InterruptedException", e); } profiler.stop(); profiler.setLogger(log); profiler.log(); } /** 收到ZooKeeper的WatchedEvent */ @Override public void process(WatchedEvent event) { log.info("event = {}", event); if (Event.EventType.None.equals(event.getType())) { // 连接状态发生变化 if (Event.KeeperState.SyncConnected.equals(event.getState())) { // 连接建立成功 connectedSemaphore.countDown(); } } }}

修改代码之后的执行记录日志如下,可以看到等待连接成功的Event耗时9秒多。网络上有文章说关闭防火墙可以秒连,但我测试过,没发现有什么变化,使用systemctl stop firewalld之后重新执行程序,仍然需要9秒多。

[INFO] - ZooKeeperWatcher.process(61) - event = WatchedEvent state:SyncConnected type:None path:null[DEBUG] - ZooKeeperWatcher.log(201) -+ Profiler [连接到ZooKeeper]|-- elapsed time [开始链接] 78.912 milliseconds.|-- elapsed time [等待连接成功的Event] 9330.606 milliseconds.|-- Total [连接到ZooKeeper] 9409.926 milliseconds.[INFO] - ZooKeeperWatcher.readNodeData(95) - /watcher 不存在

5 读取WatchedEvent

前面的代码,只是处理了建立连接成功时的Event,下面再来看看读取数据的过程。关键代码如下:


if (Event.EventType.NodeDataChanged.equals(event.getType()) || Event.EventType.NodeCreated.equals(event.getType())) { String path = event.getPath(); if (path != null && path.equals(zNode)) { // 节点数据被修改 readNodeData(); }}/** 读节点数据 */private void readNodeData() { try { Stat stat = new Stat(); byte[] data = zk.getData(zNode, true, stat); if (data != null) { log.info("{}, value={}, version={}", zNode, new String(data), stat.getVersion()); } } catch (KeeperException e) { log.info("{} 不存在", zNode); } catch (InterruptedException e) { log.error("InterruptedException", e); }}

当接收到创建节点和修改节点的WatchedEvent,都会将数据读出并打印在控制台。

6 调整后的完整程序清单

对前面的代码做了部分调整,同时添加了退出系统的机制:节点被删除。

package tech.codestory.zookeeper.watcher;import java.io.IOException;import java.util.concurrent.CountDownLatch;import org.apache.zookeeper.*;import org.apache.zookeeper.data.Stat;import org.slf4j.profiler.Profiler;import lombok.extern.slf4j.Slf4j;/** * 用于测试 ZooKeeper的 WatchedEvent用法 * @author code story * @date 2019/8/13 */@Slf4jpublic class ZooKeeperWatcher implements Watcher, Runnable { /** 等待连接建立成功的信号 */ private CountDownLatch connectedSemaphore = new CountDownLatch(1); /** 退出系统的信号 */ static Integer quitSemaphore = Integer.valueOf(-1); String zNode; ZooKeeper zk; public ZooKeeperWatcher(String hostPort, String zNode) throws KeeperException, IOException { this.zNode = zNode; Profiler profiler = new Profiler("连接到ZooKeeper"); profiler.start("开始链接"); zk = new ZooKeeper(hostPort, 3000, this); try { profiler.start("等待连接成功的Event"); connectedSemaphore.await(); } catch (InterruptedException e) { log.error("InterruptedException", e); } profiler.stop(); profiler.setLogger(log); profiler.log(); // 先读当前的数据 readNodeData(); } /** 收到ZooKeeper的WatchedEvent */ @Override public void process(WatchedEvent event) { log.info("event = {}", event); if (Event.EventType.None.equals(event.getType())) { // 连接状态发生变化 if (Event.KeeperState.SyncConnected.equals(event.getState())) { // 连接建立成功 connectedSemaphore.countDown(); } } else if (Event.EventType.NodeDataChanged.equals(event.getType()) || Event.EventType.NodeCreated.equals(event.getType())) { String path = event.getPath(); if (path != null && path.equals(zNode)) { // 节点数据被修改 readNodeData(); } } else if (Event.EventType.NodeDeleted.equals(event.getType())) { String path = event.getPath(); if (path != null && path.equals(zNode)) { synchronized (quitSemaphore) { // 节点被删除,通知退出线程 quitSemaphore.notify(); } } } } /** 读节点数据 */ private void readNodeData() { try { Stat stat = new Stat(); byte[] data = zk.getData(zNode, true, stat); if (data != null) { log.info("{}, value={}, version={}", zNode, new String(data), stat.getVersion()); } } catch (KeeperException e) { log.info("{} 不存在", zNode); try { // 目的是添加Watcher zk.exists(zNode, true); } catch (KeeperException ex) { } catch (InterruptedException ex) { } } catch (InterruptedException e) { log.error("InterruptedException", e); } } @Override public void run() { try { synchronized (quitSemaphore) { quitSemaphore.wait(); log.info("{} 被删除,退出", zNode); } } catch (InterruptedException e) { log.error("InterruptedException", e); } } /** 主程序,代码中写死了Server地址和zNode名,也可以改成从args中读取 */ public static void main(String[] args) { String hostPort = "192.168.5.128:2181"; String zNode = "/watcher"; try { new ZooKeeperWatcher(hostPort, zNode).run(); } catch (Exception e) { log.error("new ZooKeeperExecutor()", e); } }}

做一个测试,应用启动后创建节点,修改多次节点,最后删除节点,日志输出如下:

10:13:31:979 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:None path:null10:13:31:982 [DEBUG] - ZooKeeperWatcher.log(201) -+ Profiler [连接到ZooKeeper]|-- elapsed time [开始链接] 210.193 milliseconds.|-- elapsed time [等待连接成功的Event] 9385.467 milliseconds.|-- Total [连接到ZooKeeper] 9596.196 milliseconds.10:13:31:996 [INFO] - ZooKeeperWatcher.readNodeData(84) - /watcher 不存在10:15:43:451 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:NodeCreated path:/watcher10:15:43:463 [INFO] - ZooKeeperWatcher.readNodeData(81) - /watcher, value=hello zk 00, version=010:15:50:906 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:NodeDataChanged path:/watcher10:15:50:910 [INFO] - ZooKeeperWatcher.readNodeData(81) - /watcher, value=hello zk 01, version=110:15:56:004 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:NodeDataChanged path:/watcher10:15:56:007 [INFO] - ZooKeeperWatcher.readNodeData(81) - /watcher, value=hello zk 02, version=210:16:00:246 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:NodeDataChanged path:/watcher10:16:00:249 [INFO] - ZooKeeperWatcher.readNodeData(81) - /watcher, value=hello zk 03, version=310:16:06:399 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:NodeDataChanged path:/watcher10:16:06:402 [INFO] - ZooKeeperWatcher.readNodeData(81) - /watcher, value=hello zk 10, version=410:16:10:217 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:NodeDataChanged path:/watcher10:16:10:220 [INFO] - ZooKeeperWatcher.readNodeData(81) - /watcher, value=hello zk 11, version=510:16:14:444 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:NodeDataChanged path:/watcher10:16:14:447 [INFO] - ZooKeeperWatcher.readNodeData(81) - /watcher, value=hello zk 12, version=610:16:20:118 [INFO] - ZooKeeperWatcher.process(50) - event = WatchedEvent state:SyncConnected type:NodeDeleted path:/watcher10:16:20:118 [INFO] - ZooKeeperWatcher.run(101) - /watcher 被删除,退出

总结

以上所述是小编给大家介绍的Java实现ZooKeeper的zNode监控,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章