zookeeper的监听通知机制:
客户端注册监听它关心的目录节点,当目录节点发生变化(数据改变、被删除、子目录节点增加删除)时,zookeeper会通知客户端
一、先启动一个本地zookeeper, 默认端口 2181
二、创建一个节点 /mynode 并设置初始值为 node1
三、用Java API 来操作
① 先引入 pom
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.12</version>
</dependency>
② 具体代码
package com.ceair.mutms;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
public class ZookeeperSync implements Watcher{
private static CountDownLatch countDownLatch = new CountDownLatch(1);
private static ZooKeeper zk = null;
private static Stat stat = new Stat();
public static void main(String[] args) throws Exception {
// 节点路径
String path = "/mynode";
// 连接zookeeper
zk = new ZooKeeper("10.68.155.114:2181", 5000, new ZookeeperSync());
countDownLatch.await();
String str = new String(zk.getData(path, true, stat));
System.out.println("原始数据为:" + str);
Thread.sleep(1000);
}
@Override
public void process(WatchedEvent event) {
if (KeeperState.SyncConnected == event.getState()) {
System.out.println("zk连接成功通知");
if (EventType.None == event.getType() && null == event.getPath()) {
countDownLatch.countDown();
} else if (event.getType() == EventType.NodeDataChanged) {
try {
String str = new String(zk.getData(event.getPath(), true, stat));
System.out.println("数据已修改,新值为:" + str);
} catch (Exception e) {
}
}
}
}
}
③ 启动代码, 并把数据改为node2
结果:
zk连接成功通知
原始数据为:node1
zk连接成功通知
数据已修改,新值为:node2