上一篇 <<<Zookeeper示例之分布式锁
下一篇 >>>Zookeeper示例之集群请求
监听工作原理:
Zookeeper的Watcher机制主要包括客户端线程、服务端WatcherManager、Zookeeper服务器三部分,客户端在向Zookeeper服务器注册的同时,会将Watcher对象存储在客户端的WatcherManager当中,当Zookeeper服务器触发Watcher事件后,会向客户端发送通知(WatchedEvent),客户端线程从WatcherManager中取出对应的Watcher对象来执行回调逻辑。
/**子节点有变动监听*/
zkClient.subscribeChildChanges(path, new IZkChildListener() {
@Override
public void handleChildChange(String s, List<String> list) throws Exception {
System.out.println("s:"+s);
System.out.println("子节点变动:");
list.forEach(System.out::println);
}
});
/**变动或删除监听*/
zkClient.subscribeDataChanges(path, new IZkDataListener() {
@Override
public void handleDataChange(String s, Object o) throws Exception {
System.out.println("s:"+s+"\t o:"+o);
}
@Override
public void handleDataDeleted(String s) throws Exception {
System.out.println("s:"+s+"节点被删除");
}
});
/**状态监听*/
zkClient.subscribeStateChanges(new IZkStateListener() {
@Override
public void handleStateChanged(Watcher.Event.KeeperState keeperState) throws Exception {
}
@Override
public void handleNewSession() throws Exception {
}
@Override
public void handleSessionEstablishmentError(Throwable throwable) throws Exception {
}
});
推荐阅读:
<<<Zookeeper基础知识及应用场景
<<<Zookeeper如何实现分布式锁
<<<CAP理论和Base理论
<<<Zookeeper选举的策略
<<<为什么Zookeeper集群节点一定要是奇数
<<<Zookeeper在后期新增zk节点时如何提高选举效率问题
<<<Zookeeper如何保证节点一致性问题
<<<Zookeeper的Zab一致性协议原理
<<<Zookeeper实现哨兵选举机制
<<<Zookeeper示例之访问权限控制
<<<Zookeeper示例之服务发现与治理
<<<Zookeeper示例之分布式锁
<<<Zookeeper示例之集群请求
<<<Linux环境安装Zookeeper
<<<Zookeeper配置文件介绍
<<<Zookeeper常见问题
<<<Eureka与Zookeeper有啥区别?
<<<Zookeeper常用命令