/**
* Register a watcher for a particular path.
*/
abstract class WatchRegistration {
//Watcher和clientPath组织在一起,一个Watcher对应一个具体的path,一个具体
//的path可以绑定多个Watcher?
private Watcher watcher;
private String clientPath;
public WatchRegistration(Watcher watcher, String clientPath)
{
this.watcher = watcher;
this.clientPath = clientPath;
}
//获取Watcher集合,Map的key是clientPath
//抽象类,需要实现类进行实现
abstract protected Map<String, Set<Watcher>> getWatches(int rc);
/**
* Register the watcher with the set of watches on path.
* @param rc the result code of the operation that attempted to
* add the watch on the path.
*/
public void register(int rc) {
if (shouldAddWatch(rc)) { //抽象累默认rc为0,则添加,实现类可以改写
Map<String, Set<Watcher>> watches = getWatches(rc);
synchronized(watches) {//实现类返回的watches必须为非null
//获取clientPath对应的Watcher集合
Set<Watcher> watchers = watches.get(clientPath);
if (watchers == null) {//Set唯恐,构造Set,并设置到Map中
watchers = new HashSet<Watcher>();
watches.put(clientPath, watchers);
}
//将watcher添加到Set中
watchers.add(watcher);
}
}
}
/**
* Determine whether the watch should be added based on return code.
* @param rc the result code of the operation that attempted to add the
* watch on the node
* @return true if the watch should be added, otw false
*/
protected boolean shouldAddWatch(int rc) {
return rc == 0;
}
}
接下来简单下分析WatcherRegistration的实现类,
/** Handle the special case of exists watches - they add a watcher
* even in the case where NONODE result code is returned.
*/
//一个zookeeper客户端调用Zookeeper.exists方法,即使znode不存在,也会添加监听这个znode的创建
//如果另外一个zookeeper客户端创建这个znode,上面的watcher也会收到这个事件
class ExistsWatchRegistration extends WatchRegistration {
public ExistsWatchRegistration(Watcher watcher, String clientPath) {
super(watcher, clientPath);
}
@Override
protected Map<String, Set<Watcher>> getWatches(int rc) {
//如果znode存在,那么返回Zookeeper的实例的watchManager实例的dataWatches,否则返回watchManager实例的existWatches
//zookeeper的实例的watchManager实例的dataWatches和existWatches表示什么含义??zookeeper应该把watcher进行了分类
//dataWatch表示数据变化类(NodeDataChangeEvent)的watch,existWatch表示存在类的watch
return rc == 0 ? watchManager.dataWatches : watchManager.existWatches;
}
@Override
protected boolean shouldAddWatch(int rc) {
return rc == 0 || rc == KeeperException.Code.NONODE.intValue(); //znode不存在,调用zookeeper.exists也可以添加这个watcher,
}
}