8.使用Exists监控ZNode的三大Change事件
一、 zookeeper是一个分布式的协调程序(所有程序都是通过订阅它来相互感知)
1. tcp(长链接) + watcher
server -》client
client -》server
2. Driver 中的方法 exists() 监控一个znode的 CURD 的操作。
![](https://images2018.cnblogs.com/blog/514661/201803/514661-20180315172309750-2131363306.png)
client1 client2 同时订阅 baidu节点
通过对baidu节点的CURD操作,exists就会监控到,从而通知客户端
接下来是C#代码的实现
1. 实现接口 IWatcher
public class ExistsWatcher : IWatcher { private ZooKeeper _zookeeper = null; public ExistsWatcher(ZooKeeper zookeeper) { _zookeeper = zookeeper; } public void Process(WatchedEvent @event) { Console.WriteLine("path={0},state={1},type={2}", @event.Path, @event.State, @event.Type); //重新注册 exists _zookeeper.Exists(@event.Path, this); } }
2. 注册zookeeper ZookeeperWatcher的实现看 上一节课代码
ZooKeeper zookeeper = new ZooKeeper("192.168.84.136:2181", TimeSpan.FromSeconds(5),new ZookeeperWatcher()); //通过wait函数,等待ZookeeperWatcher 回调函数执行成功 ZookeeperWatcher.countdownEvent.Wait(); var list = zookeeper.GetChildren("/", false); #region 第8节try { Stat stat = new Stat(); stat = zookeeper.Exists("/google", new ExistsWatcher(zookeeper)); } catch (KeeperException ex) { throw new Exception(ex.Message); } #endregion
注意:
client -》server watcher 监控是一次性的,
client 需要在wathcer接收到通知后,从新注册exists
![](https://images2018.cnblogs.com/blog/514661/201803/514661-20180315172746546-269945453.png)
执行了一次创建,一次删除,客户端都收到了通知
![](https://images2018.cnblogs.com/blog/514661/201803/514661-20180315172813863-672339685.png)
3. exists可以监控那些事件
NodeDeleted,NodeCreated,NodeDataChanged
4. exists 应用场景
master -》 backup 双机热备
【临时节点】
zookeeper本质就是一个协调程序。