zk的watch模型

牧云@^-^@ 提交于 2019-11-30 13:22:19

WatchManager中watch机制

watcher作用:通知状态与事件类型 接口定义了process方法,定义了Event接口,包含KeeperState(通知时zk状态),EventType说明event类型

 

 

void process(WatchedEvent event);回调函数实现该函数,表示该event执行行为相关逻辑

 

WatchedEvent

描述zk检测到的状态变化事件,回应变化,发生了什么,zk当前状态,发生事件znode的路径

/**将属性转换成网络传输的WatcherEvent

* Convert WatchedEvent to type that can be sent over network

*/

public WatcherEvent getWrapper() {

return new WatcherEvent(eventType.getIntValue(), keeperState.getIntValue(), path);

}

WatcherEvent

是一个接口,实现了Record,属性有type,state,path,是网络传输的封装

 

ClientWatchManager接口 

根据event得到需要通知的watcher集合,实现类为ZKWatcherManager

 

属性:

private final Map<String, Set<Watcher>> dataWatches = new HashMap<String, Set<Watcher>>();//数据监听集合
private final Map<String, Set<Watcher>> existWatches = new HashMap<String, Set<Watcher>>();//已经存在监听集合
private final Map<String, Set<Watcher>> childWatches = new HashMap<String, Set<Watcher>>();//子节点监听集合
private boolean disableAutoWatchReset;

ZKWatchManager(boolean disableAutoWatchReset) {
    this.disableAutoWatchReset = disableAutoWatchReset;
}

protected volatile Watcher defaultWatcher;

 

方法:添加watcher

删除watcher 三种类型节点的集合变化

涉及监听类型 enum WatcherType { Children(1), Data(2), Any(3); }

materialize()实现方法

WatcherSetEventPair

将event以及对应需要触发的watches集合进行组合绑定,是一个包装类

 

private static class WatcherSetEventPair {

    private final Set<Watcher> watchers;
    private final WatchedEvent event;

    public WatcherSetEventPair(Set<Watcher> watchers, WatchedEvent event) {
        this.watchers = watchers;
        this.event = event;
    }

}

UML类图

 

zk中引入watcher机制来实现通知功能

zk允许客户端向服务端注册一个监听,指定事件触发监听时,服务端向客户端发送监听事件通知,以便客户端完成逻辑操作

特性:

一次性,watcher被触发,zk都将它从相应的相应存储中移除,注册一次,触发一次

客户端串行执行,客户端watcher回调是一个串行过程

轻量:包含事件类型 通知状态,节点路径

 

思考:

1 从哪里看出watcher在客户端是一次性的?

2 三种类型的watcher有什么关系吗?

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!