Watcher机制(二)WatchManager

简介: 本文深入分析ZooKeeper中WatchManager类的源码,重点解析其核心数据结构与方法。通过watchTable和watch2Paths两个映射维护路径与Watcher间的双向关系,实现高效的事件监听管理。类中size、addWatch、removeWatcher、triggerWatch等同步方法确保线程安全,支持Watcher的添加、删除与事件触发;dumpWatches则用于调试信息输出。整体设计简洁高效,是ZooKeeper事件通知机制的核心组件。(238字)

一、前言
  前面已经分析了Watcher机制中的第一部分,即在org.apache.zookeeper下的相关类,接着来分析org.apache.zookeeper.server下的WatchManager类。
二、WatchManager源码分析
2.1 类的属性 
public class WatchManager {
// Logger
private static final Logger LOG = LoggerFactory.getLogger(WatchManager.class);

// watcher表
private final HashMap<String, HashSet<Watcher>> watchTable =
    new HashMap<String, HashSet<Watcher>>();

// watcher到节点路径的映射
private final HashMap<Watcher, HashSet<String>> watch2Paths =
    new HashMap<Watcher, HashSet<String>>();

}
说明:WatcherManager类用于管理watchers和相应的触发器。watchTable表示从节点路径到watcher集合的映射,而watch2Paths则表示从watcher到所有节点路径集合的映射。
2.2 核心方法分析

  1. size方法
    public synchronized int size(){
    int result = 0;
    for(Set watches : watchTable.values()) { // 遍历watchTable所有的值集合(HashSet集合)
     // 每个集合大小累加
     result += watches.size();
    
    }
    // 返回结果
    return result;
    }
    说明:可以看到size方法是同步的,因此在多线程环境下是安全的,其主要作用是获取watchTable的大小,即遍历watchTable的值集合。
  2. addWatch方法
    public synchronized void addWatch(String path, Watcher watcher) {
    // 根据路径获取对应的所有watcher
    HashSet list = watchTable.get(path);
    if (list == null) { // 列表为空

     // don't waste memory if there are few watches on a node
     // rehash when the 4th entry is added, doubling size thereafter
     // seems like a good compromise
     // 新生成watcher集合
     list = new HashSet<Watcher>(4);
     // 存入watcher表
     watchTable.put(path, list);
    

    }
    // 将watcher直接添加至watcher集合
    list.add(watcher);

    // 通过watcher获取对应的所有路径
    HashSet paths = watch2Paths.get(watcher);
    if (paths == null) { // 路径为空

     // cnxns typically have many watches, so use default cap here
     // 新生成hash集合
     paths = new HashSet<String>();
     // 将watcher和对应的paths添加至映射中
     watch2Paths.put(watcher, paths);
    

    }
    // 将路径添加至paths集合
    paths.add(path);
    }
    说明:addWatch方法同样是同步的,其大致流程如下
      ① 通过传入的path(节点路径)从watchTable获取相应的watcher集合,进入②
      ② 判断①中的watcher是否为空,若为空,则进入③,否则,进入④
      ③ 新生成watcher集合,并将路径path和此集合添加至watchTable中,进入④【类似缓存操作】
      ④ 将传入的watcher添加至watcher集合,即完成了path和watcher添加至watchTable的步骤,进入⑤
      ⑤ 通过传入的watcher从watch2Paths中获取相应的path集合,进入⑥
      ⑥ 判断path集合是否为空,若为空,则进入⑦,否则,进入⑧
      ⑦ 新生成path集合,并将watcher和paths添加至watch2Paths中,进入⑧
      ⑧ 将传入的path(节点路径)添加至path集合,即完成了path和watcher添加至watch2Paths的步骤。
    综上:addWatche方法会将:
    1.入参所对应的watcher添加到入参path所对应的全部Watcher集合中,如path下已有则添加,没有创建新的并添加进去;
    2.入参所对应的path添加到入参watcher所对应给的所有路径集合中,如watcher对应路径为空则创建新的集合进行添加,非空将入参path直接添加进去。

  3. removeWatcher方法  
    public synchronized void removeWatcher(Watcher watcher) {
    // 从wach2Paths中移除watcher,并返回watcher对应的path集合
    HashSet paths = watch2Paths.remove(watcher);
    if (paths == null) { // 集合为空,直接返回
     return;
    
    }
    for (String p : paths) { // 遍历路径集合
     // 从watcher表中根据路径取出相应的watcher集合
     HashSet<Watcher> list = watchTable.get(p);
     if (list != null) { // 若集合不为空
         // 从list中移除该watcher
         list.remove(watcher);
         if (list.size() == 0) { // 移除后list为空,则从watch表中移出
             watchTable.remove(p);
         }
     }
    
    }
    }
    说明:removeWatcher用作从watch2Paths和watchTable中中移除该watcher,其大致步骤如下
      ① 从watch2Paths中移除传入的watcher,并且返回该watcher对应的路径集合,进入②
      ② 判断返回的路径集合是否为空,若为空,直接返回,否则,进入③
      ③ 遍历②中的路径集合,对每个路径,都从watchTable中取出与该路径对应的watcher集合,进入④
      ④ 若③中的watcher集合不为空,则从该集合中移除watcher,并判断移除元素后的集合大小是否为0,若为0,进入⑤
      ⑤ 从watchTable中移除路径
  4. triggerWatch方法
    public Set triggerWatch(String path, EventType type, Set supress) {
    // 根据事件类型、连接状态、节点路径创建WatchedEvent
    WatchedEvent e = new WatchedEvent(type, KeeperState.SyncConnected, path);

    // watcher集合
    HashSet watchers;
    synchronized (this) { // 同步块

     // 从watcher表中移除path,并返回其对应的watcher集合
     watchers = watchTable.remove(path);
     if (watchers == null || watchers.isEmpty()) { // watcher集合为空
         if (LOG.isTraceEnabled()) { 
             ZooTrace.logTraceMessage(LOG, ZooTrace.EVENT_DELIVERY_TRACE_MASK,
                                      "No watchers for " + path);
         }
         // 返回
         return null;
     }
     for (Watcher w : watchers) { // 遍历watcher集合
         // 根据watcher从watcher表中取出路径集合
         HashSet<String> paths = watch2Paths.get(w);
         if (paths != null) { // 路径集合不为空
             // 则移除路径
             paths.remove(path);
         }
     }
    

    }
    for (Watcher w : watchers) { // 遍历watcher集合

     if (supress != null && supress.contains(w)) { // supress不为空并且包含watcher,则跳过
         continue;
     }
     // 进行处理
     w.process(e);
    

    }
    return watchers;
    }
     说明:该方法主要用于触发watch事件,并对事件进行处理。其大致步骤如下
      ① 根据事件类型、连接状态、节点路径创建WatchedEvent,进入②
      ② 从watchTable中移除传入的path对应的键值对,并且返回path对应的watcher集合,进入③
      ③ 判断watcher集合是否为空,若为空,则之后会返回null,否则,进入④
      ④ 遍历②中的watcher集合,对每个watcher,从watch2Paths中取出path集合,进入⑤
      ⑤ 判断④中的path集合是否为空,若不为空,则从集合中移除传入的path。进入⑥
      ⑥ 再次遍历watcher集合,对每个watcher,若supress不为空并且包含了该watcher,则跳过,否则,进入⑦
      ⑦ 调用watcher的process方法进行相应处理,之后返回watcher集合。【这里的process具体怎么执行的呢】

  5. dumpWatches方法
    public synchronized void dumpWatches(PrintWriter pwriter, boolean byPath) {
    if (byPath) { // 控制写入watchTable或watch2Paths
     for (Entry<String, HashSet<Watcher>> e : watchTable.entrySet()) { // 遍历每个键值对
         // 写入键
         pwriter.println(e.getKey());
         for (Watcher w : e.getValue()) { // 遍历值(HashSet<Watcher>)
             pwriter.print("\t0x");
             pwriter.print(Long.toHexString(((ServerCnxn)w).getSessionId()));
             pwriter.print("\n");
         }
     }
    
    } else {
     for (Entry<Watcher, HashSet<String>> e : watch2Paths.entrySet()) { // 遍历每个键值对
         // 写入"0x"
         pwriter.print("0x");
         pwriter.println(Long.toHexString(((ServerCnxn)e.getKey()).getSessionId()));
         for (String path : e.getValue()) { // 遍历值(HashSet<String>)
             // 
             pwriter.print("\t");
             pwriter.println(path);
         }
     }
    
    }
    }
      说明:dumpWatches用作将watchTable或watch2Paths写入磁盘。
    三、总结
      WatchManager类用作管理watcher、其对应的路径以及触发器,其方法都是针对两个映射的操作。
相关文章
|
12月前
|
Java 大数据 Apache
Excel工具-HUTOOL-输出Excel
Hutool基于Apache POI封装了Excel读写功能,提供ExcelWriter和BigExcelWriter类,支持写出List、Map、Bean等数据类型到Excel,可自定义样式、多sheet操作,并解决大数据量导出时的内存溢出问题,适用于文件导出、客户端下载等场景。
|
12月前
|
Dubbo Java 应用服务中间件
Feign远程调用
本章介绍如何用Feign替代RestTemplate实现更优雅的HTTP跨服务调用。通过引入Feign,解决服务地址硬编码、代码可读性差等问题,结合注册中心实现声明式远程调用。内容涵盖Feign基本使用、自定义配置(如日志级别)、连接池优化(如Apache HttpClient),并探讨继承与抽取两种最佳实践方案,提升微服务间通信的可维护性与扩展性。
|
12月前
|
Apache
Excel工具-HUTOOL-读取Excel
基于Hutool和Apache POI,封装Excel读取工具,支持xls/xlsx格式。可读取为List、Map或Bean,提供Sax模式(Excel03SaxReader/Excel07SaxReader)高效处理大文件,避免内存溢出,适用于海量数据流式读取。
|
12月前
|
Java 数据库 Sentinel
服务保护、分布式事务
本课程深入讲解微服务保护与分布式事务控制。内容涵盖:微服务雪崩问题及熔断、降级、限流、线程隔离等防护机制;基于Sentinel实现熔断降级与流量控制;掌握FallbackFactory与@SentinelResource注解的使用;理解CAP原理与分布式事务场景;通过Seata实现AT模式分布式事务,保障系统高可用与数据一致性。(238字)
|
12月前
|
XML Dubbo Java
搭建dubbo-zk应用
基于Spring Boot 2.2.2与Dubbo 2.0.0,构建ZooKeeper注册中心的分布式服务架构。通过Maven多模块设计,分离API、Provider与Consumer,实现服务暴露与远程调用,结合Lombok简化开发,完成Dubbo服务的注册、发现与HTTP接口验证。
|
12月前
|
Dubbo Java 应用服务中间件
入门运行Soul
Soul 是基于 WebFlux 的高性能响应式 API 网关,支持 Dubbo、Spring Cloud、Spring Boot,具备跨语言、异步、低延迟(1~2ms)特性。采用插件化设计,支持热插拔、动态流量控制、A/B 测试、蓝绿发布,内置鉴权、限流、熔断等丰富插件,数据同步支持 WebSocket、HTTP 长轮询、Zookeeper。
|
12月前
|
消息中间件 算法 网络协议
选举机制理解描述
本文深入解析Zookeeper的Leader选举机制,涵盖启动期与运行期的选举流程,详述FastLeaderElection算法核心规则:优先比较ZXID(数据最新性),再比较SID(服务器标识)。通过投票PK、逻辑时钟(electionEpoch)同步与状态变更,确保集群在无主或主节点故障时快速选出新Leader,保障分布式数据一致性。同时介绍QuorumCnxManager网络通信、选票管理及多轮投票统计等实现细节,揭示Zookeeper高可用背后的原理。
|
12月前
Watcher机制(三)之ZooKeeper
本文深入分析ZooKeeper客户端核心类,涵盖其内部类结构、属性、构造函数及关键操作方法。重点解析WatchRegistration体系及create、delete、exists等同步/异步实现机制,揭示ZooKeeper客户端与服务端交互原理。
|
12月前
|
关系型数据库 MySQL Java
开发环境搭建
工欲善其事,必先利其器。学习前请确保电脑内存16G以上(推荐32G),建议配备便携显示器分屏开发以提升效率。下载并配置虚拟机(IP:192.168.101.68)、安装VMware、IDEA、Maven、Git等环境,导入黑马商城项目,搭建前后端运行环境,完成数据库初始化与Nginx前端部署,开启高效学习之旅。(239字)
|
12月前
|
消息中间件 算法 网络协议
选举机制源码分析
本文深入解析ZooKeeper中FastLeaderElection选举算法的源码实现,涵盖Election接口、FastLeaderElection核心类及其内部类Notification、ToSend、Messenger的工作机制。重点分析了选票收发、PK规则(epoch、zxid、id)、投票统计与Leader确定流程,全面揭示ZooKeeper领导者选举的底层原理与实现细节。