47-微服务技术栈(高级):分布式协调服务zookeeper源码篇(Watcher机制-2[WatchManager])

简介: 前面已经分析了Watcher机制中的第一部分,即在org.apache.zookeeper下的相关类,接着来分析org.apache.zookeeper.server下的WatchManager类。

一、前言

  前面已经分析了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<Watcher> watches : watchTable.values()) { // 遍历watchTable所有的值集合(HashSet<Watcher>集合)

       // 每个集合大小累加

       result += watches.size();

   }

   // 返回结果

   return result;

}

说明:可以看到size方法是同步的,因此在多线程环境下是安全的,其主要作用是获取watchTable的大小,即遍历watchTable的值集合。

2. addWatch方法

public synchronized void addWatch(String path, Watcher watcher) {

   // 根据路径获取对应的所有watcher

   HashSet<Watcher> 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<String> 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<String> 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<Watcher> triggerWatch(String path, EventType type, Set<Watcher> supress) {

   // 根据事件类型、连接状态、节点路径创建WatchedEvent

   WatchedEvent e = new WatchedEvent(type, KeeperState.SyncConnected, path);


   // watcher集合

   HashSet<Watcher> 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、其对应的路径以及触发器,其方法都是针对两个映射的操作。

相关文章
|
4月前
|
存储 安全 Java
管理 Spring 微服务中的分布式会话
在微服务架构中,管理分布式会话是确保用户体验一致性和系统可扩展性的关键挑战。本文探讨了在 Spring 框架下实现分布式会话管理的多种方法,包括集中式会话存储和客户端会话存储(如 Cookie),并分析了它们的优缺点。同时,文章还涵盖了与分布式会话相关的安全考虑,如数据加密、令牌验证、安全 Cookie 政策以及服务间身份验证。此外,文中强调了分布式会话在提升系统可扩展性、增强可用性、实现数据一致性及优化资源利用方面的显著优势。通过合理选择会话管理策略,结合 Spring 提供的强大工具,开发人员可以在保证系统鲁棒性的同时,提供无缝的用户体验。
|
5月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
968 3
|
3月前
|
存储 运维 监控
120_检查点管理:故障恢复 - 实现分布式保存机制
在大型语言模型(LLM)的训练过程中,检查点管理是确保训练稳定性和可靠性的关键环节。2025年,随着模型规模的不断扩大,从百亿参数到千亿参数,训练时间通常长达数周甚至数月,硬件故障、软件错误或网络中断等问题随时可能发生。有效的检查点管理机制不仅能够在故障发生时快速恢复训练,还能优化存储使用、提高训练效率,并支持实验管理和模型版本控制。
120_检查点管理:故障恢复 - 实现分布式保存机制
|
3月前
|
负载均衡 Java API
《深入理解Spring》Spring Cloud 构建分布式系统的微服务全家桶
Spring Cloud为微服务架构提供一站式解决方案,涵盖服务注册、配置管理、负载均衡、熔断限流等核心功能,助力开发者构建高可用、易扩展的分布式系统,并持续向云原生演进。
|
9月前
|
人工智能 安全 Java
智慧工地源码,Java语言开发,微服务架构,支持分布式和集群部署,多端覆盖
智慧工地是“互联网+建筑工地”的创新模式,基于物联网、移动互联网、BIM、大数据、人工智能等技术,实现对施工现场人员、设备、材料、安全等环节的智能化管理。其解决方案涵盖数据大屏、移动APP和PC管理端,采用高性能Java微服务架构,支持分布式与集群部署,结合Redis、消息队列等技术确保系统稳定高效。通过大数据驱动决策、物联网实时监测预警及AI智能视频监控,消除数据孤岛,提升项目可控性与安全性。智慧工地提供专家级远程管理服务,助力施工质量和安全管理升级,同时依托可扩展平台、多端应用和丰富设备接口,满足多样化需求,推动建筑行业数字化转型。
339 5
|
12月前
|
人工智能 安全 Java
微服务引擎 MSE:打造通用的企业级微服务架构
微服务引擎MSE致力于打造通用的企业级微服务架构,涵盖四大核心内容:微服务技术趋势与挑战、MSE应对方案、拥抱开源及最佳实践。MSE通过流量入口、内部流量管理、服务治理等模块,提供高可用、跨语言支持和性能优化。此外,MSE坚持开放,推动云原生与AI融合,助力企业实现无缝迁移和高效运维。
567 1
|
Java 关系型数据库 数据库
微服务SpringCloud分布式事务之Seata
SpringCloud+SpringCloudAlibaba的Seata实现分布式事务,步骤超详细,附带视频教程
908 1
|
存储 运维 数据可视化
如何为微服务实现分布式日志记录
如何为微服务实现分布式日志记录
821 1
|
5月前
|
存储 负载均衡 NoSQL
【赵渝强老师】Redis Cluster分布式集群
Redis Cluster是Redis的分布式存储解决方案,通过哈希槽(slot)实现数据分片,支持水平扩展,具备高可用性和负载均衡能力,适用于大规模数据场景。
422 2
|
5月前
|
存储 缓存 NoSQL
【📕分布式锁通关指南 12】源码剖析redisson如何利用Redis数据结构实现Semaphore和CountDownLatch
本文解析 Redisson 如何通过 Redis 实现分布式信号量(RSemaphore)与倒数闩(RCountDownLatch),利用 Lua 脚本与原子操作保障分布式环境下的同步控制,帮助开发者更好地理解其原理与应用。
365 6

相关产品

  • 微服务引擎