Zookeeper分布式入门——ZK的Java客户端Curator(4)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_37338761/article/details/100023659

ZK的Java客户端Curator(4)


实践4

1.watcher 事件

当使用usingWatcher的时候,监听只会触发一次,监听完毕后就销毁

// watcher 事件  当使用usingWatcher的时候,监听只会触发一次,监听完毕后就销毁
cto.client.getData().usingWatcher(new MyCuratorWatcher()).forPath(nodePath);
//cto.client.getData().usingWatcher(new MyWatcher()).forPath(nodePath);

2.监听缓存

  • NodeCache: 监听数据节点的变更,会触发事件。一直运行监听,增删改操作都会输出节点信息 nodePath为监听路径。
  • nodeCache.start(true);为开启监听 初始化使用true,可以在获取客户端进行连接时节点的数据。
  • nodeCache.getListenable()
    获取所有监听列表。nodeCache.getListenable()也有remove事件,用来移除监听。
  • 只要有事件发生就会触发NodeCacheListener的nodeChanged()方法
// 为节点添加watcher
// NodeCache: 监听数据节点的变更,会触发事件
final NodeCache nodeCache = new NodeCache(cto.client, nodePath);
// buildInitial : 初始化的时候获取node的值并且缓存
nodeCache.start(true);
if (nodeCache.getCurrentData() != null) {
	System.out.println("节点初始化数据为:" + new String(nodeCache.getCurrentData().getData()));
} else {
	System.out.println("节点初始化数据为空...");
}
nodeCache.getListenable().addListener(new NodeCacheListener() {
	public void nodeChanged() throws Exception {
		if (nodeCache.getCurrentData() == null) {
			System.out.println("空");
			return;
		}
		String data = new String(nodeCache.getCurrentData().getData());
		System.out.println("节点路径:" + nodeCache.getCurrentData().getPath() + "数据:" + data);
	}
});

猜你喜欢

转载自blog.csdn.net/qq_37338761/article/details/100023659
今日推荐