[zookeeper]zookeeper系列三:zookeeper中watcher的使用及原理

ZooKeeper系列:zk中的watch Watch就是监听,观察。其实就是客户端注册watch,然后服务端发生节点数据变化的时候会触发watch事件,接着回调客户端。 阅读详情

watcher解决的问题

在进入watcher之前我们先试想在应用服务器集群中可能存在的两个问题:

  1. 因为集群中有很多机器,当某个通用的配置发生变化后,怎么让自动的让所有服务器的配置统一生效?
  2. 当集群中某个节点宕机,如何让集群中的其他节点知道?

为了解决这两个问题,zookeeper引入了watcher机制来实现发布/订阅功能,能够让多个订阅者同时监听某一个主题对象,当这个主题对象自身状态发生变化时,会通知所有订阅者。

watcher基本原理

zookeeper中实现watcher需要有三个部分,如下图所示:

watcher基本原理

分别是zookeeper服务端、客户端以及客户端的watchManager。

如图所示,客户端向zk注册watcher的同时,会将客户端的watcher对象存储在客户端的WatchManager中;zk服务器触发watch事件后,会向客户端发送通知,客户端线程从watchManager中取出对应watcher执行。

客户端如何实现事件通知的动作

客户端只需定义一个类实现org.apache.zookeeper.Watcher接口并实现接口中的如下方法:

abstract public void process(WatchedEvent event);

即可在得到通知后执行相应的动作。参数org.apache.zookeeper.WatchedEvent是zk服务端传过来的事件,有三个成员:

final private KeeperState keeperState; // 通知状态
final private EventType eventType; // 事件类型
private String path; // 哪个节点发生的时间

分别代表通知的状态、事件类型和发生事件的节点。

keeperState是个枚举对象,代表客户端和zk服务器的链接状态,定义如下:

/**
 * Enumeration of states the ZooKeeper may be at the event
 */
 public enum KeeperState {
      /** Unused, this state is never generated by the server */
      @Deprecated
      Unknown (-1),

      /** The client is in the disconnected state - it is not connected
       * to any server in the ensemble. */
       Disconnected (0),

      /** Unused, this state is never generated by the server */
       @Deprecated
       NoSyncConnected (1),

     /** The client is in the connected state - it is connected
      * to a server in the ensemble (one of the servers specified
      * in the host connection parameter during ZooKeeper client
      * creation). 
      * /
      SyncConnected (3),

      /**
       * Auth failed state
       */
       AuthFailed (4),

      /**
       * The client is connected to a read-only server, that is the
       * server which is not currently connected to the majority.
       * The only operations allowed after receiving this state is
       * read operations.
       * This state is generated for read-only clients only since
       * read/write clients aren't allowed to connect to r/o servers.
       */
       ConnectedReadOnly (5),

       /**
        * SaslAuthenticated: used to notify clients that they are SASL-authenticated,
        * so that they can perform Zookeeper actions with their SASL-authorized permissions.
        */
        SaslAuthenticated(6),

       /** The serving cluster has expired this session. The ZooKeeper
        * client connection (the session) is no longer valid. You must
        * create a new client connection (instantiate a new ZooKeeper
        * instance) if you with to access the ensemble. 
        */
        Expired (-112);

        private final int intValue;     // Integer representation of value
                                        // for sending over wire

        KeeperState(int intValue) {
            this.intValue = intValue;
        }

        public int getIntValue() {
            return intValue;
        }

        public static KeeperState fromInt(int intValue) {
              switch(intValue) {
                  case   -1: return KeeperState.Unknown;
                  case    0: return KeeperState.Disconnected;
                  case    1: return KeeperState.NoSyncConnected;
                  case    3: return KeeperState.SyncConnected;
                  case    4: return KeeperState.AuthFailed;
                  case    5: return KeeperState.ConnectedReadOnly;
                  case    6: return KeeperState.SaslAuthenticated;
                  case -112: return KeeperState.Expired;

                  default:
                        throw new RuntimeException("Invalid integer value for conversion to KeeperState");
               }
        }
 }

eventType也是个枚举类型,代表节点发生的事件类型,比如创建新的子节点、改变节点数据等,定义如下:

/**
 * Enumeration of types of events that may occur on the ZooKeeper
 */
 public enum EventType {
       None (-1),
       NodeCreated (1),
       NodeDeleted (2),
       NodeDataChanged (3),
       NodeChildrenChanged (4),
       DataWatchRemoved (5),
       ChildWatchRemoved (6);

       private final int intValue;     // Integer representation of value
                                       // for sending over wire

       EventType(int intValue) {
            this.intValue = intValue;
       }

       public int getIntValue() {
            return intValue;
       }

       public static EventType fromInt(int intValue) {
            switch(intValue) {
                case -1: return EventType.None;
                case  1: return EventType.NodeCreated;
                case  2: return EventType.NodeDeleted;
                case  3: return EventType.NodeDataChanged;
                case  4: return EventType.NodeChildrenChanged;
                case  5: return EventType.DataWatchRemoved;
                case  6: return EventType.ChildWatchRemoved;

                default:
                         throw new RuntimeException("Invalid integer value for conversion to EventType");
            }
       }           
}

keeperState和eventType对应关系如下所示:

keeperState和enevtType对应关系

对于NodeDataChanged事件:无论节点数据发生变化还是数据版本发生变化都会触发(即使被更新数据与新数据一样,数据版本都会发生变化)。

对于NodeChildrenChanged事件:新增和删除子节点会触发该事件类型。

需要注意的是:WatchedEvent只是事件相关的通知,并没有对应数据节点的原始数据内容及变更后的新数据内容,因此如果需要知道变更前的数据或变更后的新数据,需要业务保存变更前的数据和调用接口获取新的数据

如何注册watcher

watcher注册api

可以在创建zk客户端实例的时候注册watcher(构造方法中注册watcher):

public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher)
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher,ZKClientConfig conf)
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly, HostProvider aHostProvider)
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly, HostProvider aHostProvider,ZKClientConfig clientConfig)
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly)
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly, ZKClientConfig conf)
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd)
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd, boolean canBeReadOnly, HostProvider aHostProvider)
public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher, long sessionId, byte[] sessionPasswd, boolean canBeReadOnly)

ZooKeeper的构造方法中传入的watcher将会作为整个zk会话期间的默认watcher,该watcher会一直保存为客户端ZKWatchManager的defaultWatcher成员,如果有其他的设置,这个watcher会被覆盖。

除了可以通过ZooKeeper类的构造方法注册watcher外,还可以通过ZooKeeper类中其他一些api来注册watcher,只不过这些api注册的watcher就不是默认watcher了(以下每个注册watcher的方法有很多个重载的方法,就不一一列举出来)。

public List<String> getChildren(final String path, Watcher watcher)
// boolean watch表示是否使用上下文中默认的watcher,即创建zk实例时设置的watcher
public List<String> getChildren(String path, boolean watch)
// boolean watch表示是否使用上下文中默认的watcher,即创建zk实例时设置的watcher
public byte[] getData(String path, boolean watch, Stat stat)
public void getData(final String path, Watcher watcher, DataCallback cb, Object ctx)
// boolean watch表示是否使用上下文中默认的watcher,即创建zk实例时设置的watcher
public Stat exists(String path, boolean watch)
public Stat exists(final String path, Watcher watcher)

watcher注册示例代码

本示例中使用zookeeper自带客户端演示watcher的使用,zookeeper自带客户端有一点需要注意:

Watcher设置后,一旦触发一次即会失效,如果需要一直监听,则需要再注册

定义默认watcher:

/**
 * 测试默认watcher
 */
public class DefaultWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {

        System.out.println("==========DefaultWatcher start==============");

        System.out.println("DefaultWatcher state: " + event.getState().name());

        System.out.println("DefaultWatcher type: " + event.getType().name());

        System.out.println("DefaultWatcher path: " + event.getPath());

        System.out.println("==========DefaultWatcher end==============");
    }
}

定义监听子节点变化的watcher:

/**
 * 用于监听子节点变化的watcher
 */
public class ChildrenWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {

        System.out.println("==========ChildrenWatcher start==============");

        System.out.println("ChildrenWatcher state: " + event.getState().name());

        System.out.println("ChildrenWatcher type: " + event.getType().name());

        System.out.println("ChildrenWatcher path: " + event.getPath());

        System.out.println("==========ChildrenWatcher end==============");
    }
}

定义监听节点变化的watcher:

public class DataWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {

        System.out.println("==========DataWatcher start==============");

        System.out.println("DataWatcher state: " + event.getState().name());

        System.out.println("DataWatcher type: " + event.getType().name());

        System.out.println("DataWatcher path: " + event.getPath());

        System.out.println("==========DataWatcher end==============");
    }
}

watcher测试代码:

public class WatcherTest {

    /**
     * 链接zk服务端的地址
     */
    private static final String CONNECT_STRING = "192.168.0.113:2181";

    public static void main(String[] args) {

        // 除了默认watcher外其他watcher一旦触发就会失效,需要充新注册,本示例中因为
        // 还未想到比较好的重新注册watcher方式(考虑到如果在Watcher中持有一个zk客户端的
        // 实例可能存在循环引用的问题),因此暂不实现watcher失效后重新注册watcher的问题,
        // 后续可以查阅curator重新注册watcher的实现方法。

        // 默认watcher
        DefaultWatcher defaultWatcher = new DefaultWatcher();
        // 监听子节点变化的watcher
        ChildrenWatcher childrenWatcher = new ChildrenWatcher();
        // 监听节点数据变化的watcher
        DataWatcher dataWatcher = new DataWatcher();
        try {
            // 创建zk客户端,并注册默认watcher
            ZooKeeper zooKeeper = new ZooKeeper(CONNECT_STRING, 100000, defaultWatcher);

            // 让默认watcher监听 /GetChildren 节点的子节点变化
            // zooKeeper.getChildren("/GetChildren", true);

            // 让childrenWatcher监听 /GetChildren 节点的子节点变化(默认watcher不再监听该节点子节点变化)
            zooKeeper.getChildren("/GetChildren", childrenWatcher);

            // 让dataWatcher监听 /GetChildren 节点本省的变化(默认watcher不再监听该节点变化)
            zooKeeper.getData("/GetChildren", dataWatcher, null);

            TimeUnit.SECONDS.sleep(1000000);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

测试过程:

首先在命令行客户端创建节点 /GetChildren

[zk: localhost:2181(CONNECTED) 133] create /GetChildren GetChildrenData
Created /GetChildren

运行测试代码WatcherTest,输出如下内容:

==========DefaultWatcher start==============
DefaultWatcher state: SyncConnected
DefaultWatcher type: None
DefaultWatcher path: null
==========DefaultWatcher end==============

可以看出在客户端第一次链接zk服务端时触发了链接成功的事件通知,该事件由默认watcher接收,导致默认watcher相关代码得到执行。

接着在命令行客户端创建子节点:

[zk: localhost:2181(CONNECTED) 134] create /GetChildren/ChildNode ChildNodeData
Created /GetChildren/ChildNode

ChildrenWatcher收到通知,/GetChildren的子节点发生变化,因此输出如下内容:

==========ChildrenWatcher start==============
ChildrenWatcher state: SyncConnected
ChildrenWatcher type: NodeChildrenChanged
ChildrenWatcher path: /GetChildren
==========ChildrenWatcher end==============

最后在命令行客户端修改 /GetChildren 节点数据:

[zk: localhost:2181(CONNECTED) 135] set /GetChildren GetChildrenDataV2
cZxid = 0xab
ctime = Sat Sep 15 03:52:48 PDT 2018
mZxid = 0xb0
mtime = Sat Sep 15 04:06:05 PDT 2018
pZxid = 0xaf
cversion = 1
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 17
numChildren = 1

DataWatcher收到通知,输出如下内容:

==========DataWatcher start==============
DataWatcher state: SyncConnected
DataWatcher type: NodeDataChanged
DataWatcher path: /GetChildren
==========DataWatcher end==============

我们可以接着在命令行客户端修改 /GetChildren 节点数据:

[zk: localhost:2181(CONNECTED) 136] set /GetChildren GetChildrenDataV3         
cZxid = 0xab
ctime = Sat Sep 15 03:52:48 PDT 2018
mZxid = 0xb1
mtime = Sat Sep 15 04:14:54 PDT 2018
pZxid = 0xaf
cversion = 1
dataVersion = 2
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 17
numChildren = 1

但WatcherTest没有任何输出了,说明DataWatcher已经失效了,要能够继续出发需要重新注册。

watcher实现源码分析

我们以注册watcher的 getData api为例,分析watcher的注册流程,以setData api为例,分析watcher的触发流程。

getData的实现在org.apache.zookeeper.ZooKeeper类中,具体代码如下:

public byte[] getData(final String path, Watcher watcher, Stat stat)
        throws KeeperException, InterruptedException
     {
        final String clientPath = path;
        PathUtils.validatePath(clientPath);

        // the watch contains the un-chroot path
        WatchRegistration wcb = null;
        if (watcher != null) {
            wcb = new DataWatchRegistration(watcher, clientPath);
        }

        final String serverPath = prependChroot(clientPath);

        RequestHeader h = new RequestHeader();
        h.setType(ZooDefs.OpCode.getData);
        GetDataRequest request = new GetDataRequest();
        request.setPath(serverPath);
        request.setWatch(watcher != null);
        GetDataResponse response = new GetDataResponse();
        ReplyHeader r = cnxn.submitRequest(h, request, response, wcb);
        if (r.getErr() != 0) {
            throw KeeperException.create(KeeperException.Code.get(r.getErr()),
                    clientPath);
        }
        if (stat != null) {
            DataTree.copyStat(response.getStat(), stat);
        }
        return response.getData();
    }

重点看:

......
WatchRegistration wcb = null;
if (watcher != null) {
      wcb = new DataWatchRegistration(watcher, clientPath);
}
......
ReplyHeader r = cnxn.submitRequest(h, request, response, wcb);
......

我们首先看org.apache.zookeeper.ZooKeeper.DataWatchRegistration和org.apache.zookeeper.ZooKeeper.WatchRegistration类的实现代码:

/**
 * Register a watcher for a particular path.
 */
public abstract class WatchRegistration {
    private Watcher watcher;
    private String clientPath;
    public WatchRegistration(Watcher watcher, String clientPath)
    {
        this.watcher = watcher;
        this.clientPath = 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)) {
             Map<String, Set<Watcher>> watches = getWatches(rc);
             synchronized(watches) {
                  Set<Watcher> watchers = watches.get(clientPath);
                  if (watchers == null) {
                       watchers = new HashSet<Watcher>();
                       watches.put(clientPath, watchers);
                  }
                  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;
    }
}

class DataWatchRegistration extends WatchRegistration {
      public DataWatchRegistration(Watcher watcher, String clientPath) {
            super(watcher, clientPath);
      }

      @Override
      protected Map<String, Set<Watcher>> getWatches(int rc) {
            return watchManager.dataWatches;
      }
}

org.apache.zookeeper.ZooKeeper.DataWatchRegistration#getWatches方法是从org.apache.zookeeper.ZooKeeper.ZKWatchManager中获取保存watcher的一个HashMap:

private final Map<String, Set<Watcher>> dataWatches =
            new HashMap<String, Set<Watcher>>();

org.apache.zookeeper.ZooKeeper.WatchRegistration#register方法显然是注册一个watcher,该方法肯定会在后续流程得到调用,事实上在getData返回数据并且判断成功后就会调用该方法将watcher加入到ZKWatchManager中,我们稍后到了这一步流程在分析,这里先有个大概的了解。

我们回到getData发送请求的代码:

ReplyHeader r = cnxn.submitRequest(h, request, response, wcb);

cnxn的类型是org.apache.zookeeper.ClientCnxn,进入到submitRequest方法:

public ReplyHeader submitRequest(RequestHeader h, Record request, Record response, WatchRegistration watchRegistration) throws InterruptedException {
    return submitRequest(h, request, response, watchRegistration, null);
}

public ReplyHeader submitRequest(RequestHeader h, Record request, Record response, WatchRegistration watchRegistration, WatchDeregistration watchDeregistration) throws InterruptedException {
    ReplyHeader r = new ReplyHeader();
    Packet packet = queuePacket(h, r, request, response, null, null, null, null, watchRegistration, watchDeregistration);
    synchronized (packet) {
        while (!packet.finished) {
             packet.wait();
        }
    }
    return r;
}

先到此为止,等有空继续完善源码分析部分(源码分析描述起来太麻烦了)。。。。。。。

Zookeeper系列——4Zookeeper的Watcher机制原理分析 Zookeeper的watcher机制应用;Zookeeper的watcher机制注册流程以及时间触发流程推导;Zookeeper的watcher机制核心源码分析 阅读详情

相关推荐

Zookeeper Watcher机制原理与代码实例讲解

Zookeeper Watcher机制原理与代码实例讲解 1.背景介绍 Zookeeper是一个分布式协调服务,广泛应用于分布式系统中,用于实现数据的同步、配置管理和命名服务等功能。Zookeeper的核心机制之一是Watcher机制,它允许客户端在Zookeeper

AI天才研究院 1013

Zookeeper的Watcher机制及Watcher原理分析

目录 1、什么是Watcher监听机制 2、Zookeeper命令实现 3、Java API实现 4、源码解析 4.1 Watcher接口 4.2 注册全局监听器 4.3 注册监听器(getChildren) 4.4 请求包入列并发送 4.5 服务器端循环监听 4.6 触发Watcher(setData) 1、什么是Watcher监听机制 Watcher 监听机制是 Zookeeper 中非常重要的特性,我们基于 zookeeper 上创建的节点,可以对这些节点绑定监听事件,比.

长沙老码农 7872

MAX96717实战:如何选择Host-to-Peripheral和Pass-Through I2C模式?附配置代码

本文深入解析MAX96717芯片的两种关键I2C模式:Host-to-Peripheral与Pass-Through。通过对比其核心差异、硬件连接考量及软件配置代码,为嵌入式开发者提供了清晰的模式选择策略与实战指南,帮助优化系统设计并避免常见通信故障。

weixin_29190573的博客 469

ZK/zookeeper常规命令 | Watch监控命令的使用 | ACL权限操作 | Four Letter Words四字命令详解 | 配置super超级用户权限 | 总结的很全面,你会喜欢吗

文章力求用最精简的语言,全面系统的介绍了zk各种命令的使用,这些命令都很重要,可以不用完全熟记,但是不可不知,温故而知新。 get set 是一些常规操作命令,Watch命令用来监听节点的各种变化(java项目实战用的比较多),nc命令有时候也不可或缺,比如dump命令。 全文根据命令的分类:常规、watch监控、Acl权限、nc四字命令,共分为四大章节。可更加目录,快速定位查看。

血煞长虹 的专栏 1万+

C#安装OpenCv及打开笔记本默认摄像头方法

C#安装OpenCv及打开笔记本默认摄像头方法

cg1135217680的博客 2575

微信中调起支付宝支付

微信中调用支付宝支付,首先我们知道微信是不能直接调用支付宝的,所以我们需要使用一个中间页提示用户在浏览器中打开,然后进行网页支付或打开app支付。以下为详细唤起支付宝的步骤、业务代码以及相关页面图。 如有问题欢迎评论留言,看到定回复哦^_^\(^o^)/~ 一、微信中唤起支付宝,有几个步骤: 1、中间页引导用户在浏览器中打开去唤起支付宝。 2、浏览器中打开支付宝或app中打开支付宝。 3...

han_calligrapher的博客 2万+

Zookeeper----watch机制核心(Watcher&&ZK状态&&事件类型)

Watcher&&ZK状态&&事件类型 watch机制测试代码 package bhz.zookeeper.watcher; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteg...

Miracle_Gaaral的博客 430

2026年9月20日 2026年CSP-S初赛真题整理

这是本次考试最难的部分,涉及Gray Code(格雷码)+ 状态压缩 + 数学推导难点解决方案关键代码问题转化将得分差转化为m−2xim - 2x[i]m−2xi高效枚举Gray Code相邻状态O(1)转移奇偶判断利用奇偶性统一条件。

weixin_51184047的博客 647

Zookeeper(7)Zookeeper的观察者(Watcher)机制是什么?

Zookeeper 的 Watcher 机制是一种高效的事件通知机制,允许客户端监视 ZNode 的数据或状态变化。Watcher 是一次性的,需要在每次事件触发后重新设置。通过上述代码示例,可以看到如何使用 Watcher 机制监视 ZNode 的数据变化,处理 Watcher 事件,并重新设置 Watcher。了解 Watcher 机制有助于在实际应用中实现高效的分布式协调和管理。

qq_43012298的博客 1320

辉芒微教程第七篇《PWM与PWM3调节LED灯的亮度》

这个其实就是PR3L = 128设置的,由于我们刚刚寄存器设置了8位模式,其设置的范围就是0-255,而128/255≈50%左右,因此PR3L就是我们的占空比调节的寄存器,我们可以通过它来调节占空比,大家可以试试它占空比设置10%,30%,60%来看看它的不同效果,灯的亮度是肯定不一样的,如果有条件的朋友,可以购买一款逻辑分析仪去看他的占空比。平平无期的这个东西有什么东东用,貌似是没什么用,只是一个概念而已,是不是不同设备可以设置1秒,3秒,10秒的周期就行?但是它占空比为什么是50%,怎么得来的?

qq_41809823的博客 838

深入理解Android音视频同步机制(三)NuPlayer的avsync逻辑

本文深入介绍了NuPlayer的avsync逻辑和原理

张晖的专栏 1万+

zookeeper中watcher的使用及原理

watcher网上 watcher解决的问题 在进入watcher之前我们先试想在应用服务器集群中可能存在的两个问题: 因为集群中有很多机器,当某个通用的配置发生变化后,怎么让自动的让所有服务器的配置统一生效? 当集群中某个节点宕机,如何让集群中的其他节点知道? 为了解决这两个问题,zookeeper引入了watcher机制来实现发布/订阅功能,能够让多个订阅者同时监听某一个主题对象,当这个主题对象自身状态发生变化时,会通知所有订阅者。 watcher基本原理 zookeeper中实现watcher需要

qq_40981804的博客 1845

Nova — GPU/vGPU 虚拟机

目录 文章目录目录云主机使用显卡的实现方式虚拟显卡物理显卡直通物理显卡虚拟化 云主机使用显卡的实现方式 采用虚拟显卡 采用物理显卡直通 采用物理显卡虚拟化 虚拟显卡 虚拟显卡技术,主要用于虚拟机 Remote Console 领域,如:VNC(Virtual Network Computing,虚拟网络计算机),它能将完整的窗口界面通过网络,传输到另一台计算机的屏幕上。 VNC 主要由 VNC server 和 VNC viewer 两部分组成。用户需先将 VNC server 安装在被远程操控的计算

烟云的计算 2437

ZooKeeper Watcher机制

要获取一个节点的数据变化,通常有两种方案: 轮询:实时性差,资源利用率低,浪费大量的 CPU 和 带宽; 事件:数据状态变更时,主动通知 Client,节省大量资源;ZK Server 通过 watcher 监视点,来实现事件通知。 而zk使用的是后一种方案,一个zk服务器集群上的节点Znode发生变化(Znode本身的增加,删除,修改,以及子Znode的变化)就可以通过Watch机制通知到客...

maoyeqiu的专栏 2387

图机器学习(7)——图神经网络 (Graph Neural Network, GNN)

图神经网络 (Graph Neural Network, GNN) 是一类专门处理图结构数据的深度学习方法。这类方法也被称为几何深度学习 (geometric deep learning),在社交网络分析、计算机图形学等众多领域正受到日益广泛的关注。在本节中,我们介绍了 GNN 的核心原理,将卷积等经典深度学习范式拓展至非欧几里得图空间,实现了局部结构与全局特征的层次化提取。

盼小辉丶的博客 1万+

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

Zookeeper——Watcher原理详解

文章目录引言正文一、如何注册监听二、如何触发监听事件三、事件类型有哪些四、Watcher可以被无限次触发么?为什么要这么设计?五、Watcher实现原理1. 客服端发送请求a. 初始化客户端并绑定Watcherb. exists/getData/getChildren绑定Watcher以及发送请求ClientCnxn.submitRequestClientCnxnSocketNIO.doTranp...

夜勿语的博客 2185

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

ZooKeeper Watcher监听机制深度解析:实现原理与源码分析

Watcher是ZooKeeper提供的发布/订阅机制,允许客户端注册对特定ZNode的关注,当该节点发生变化时,服务端会主动通知客户端。fill:#333;important;important;fill:none;color:#333;color:#333;important;fill:none;fill:#333;height:1em;Watcher机制核心1. 注册Watcher2. 存储Watcher3. 触发Watcher4. 发送通知客户端ZooKeeper服务端数据变更组件。

✨ 欢迎来到【Seal ^_^ 的CSDN博客】!✨ 3550

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

zookeeper的watcher机制

ZooKeeper 提供了分布式数据的发布/订阅功能。一个典型的发布/阅模型系统定义了一种一对多的订阅关系,能够让多个订阅者同时监听某一个主题对象,当这个主题对象自身状态变化时,会通知所有订阅者,使它们能够做出相应的处理。在 ZooKeeper 中,引入了 Watcher 机制来实现这种分布式的通知功能。 ZooKeeper 允许客户端向服务端注册一个 Watcher 监听,当服务端的一些指定事件触发了这个 Watcher,那么就会向指定客户端发送一个事件通知来实现分布式的通知功能。 简单来说客户端在向z

程铭程铭你快成名的博客 6226

【ZooKeeper】Watcher 原理

Watcher ----- 数据变更的通知 ZooKeeper 提供了分布式数据的发布/订阅功能。一个典 型的发布/订阅模型系统定义了一种一对多的订阅关系,能够让多个订阅者同时监听某一 个主题对象,当这个主题对象自身状态变化时,会通知所有订阅者,使它们能够做出相 应的处理。在 ZooKeeper中,引入了 Watcher 机制来实现这种分布式的通知功能。 ZooKeeper 允许客户端向服务端注册一个 Watcher 监听,当服务端的一些指定事件触发 了这个 Watcher, 那么就会向指定客户端发送

菜鸡也有大佬梦 1112

深入理解Zookeeper系列-4.Watcher原理

在分析问题的时候,我们所学的事件的机制、异步化、基于线程的生产者消费者模型,其实它可以在刚刚的场景中去使用,比如我们发起这个请求,他可以将其放置在队列中,通过线程去和对应的接口做远程通信,这时我们可以解决我们这端的并发量的问题,他们第三方在不改变的情况下,我们这端某种程度上提升了一定的吞吐量,然后基于事件的机制就是我们调用第三方接口给返回的时候,基于这个返回结果发送一个通知去告诉调用者结果处理完了,你去拿这个结果做后续的处理。当客户端接收到Watcher通知后,它会根据通知消息中的信息进行相应的处理。

爱吃知识的土豆倪的博客 1188

zookeeper 源码 之 watcher 原理分析

1、Watcher 的基本流程 ZooKeeper 的 Watcher 机制,总的来说可以分为三个过程: (1)客户端注册 Watcher; (2)服务器处理 Watcher; (3)客户端回调 Watcher。 客户端注册 watcher 有 3 种方式,getData、exists、getChildren; 以如下代码为例来分析整个触发机制的原理。 2、基于 zkclient 客户端发起一个数据操作 maven 依赖 <dependency> <groupId>com

跨语言,跨平台,跨应用 646

ZooKeeper Watcher 使用注意事项全面指南:避开常见陷阱

注意事项问题解决方案一次性触发Watcher只触发一次在process()中重新注册轻量级通知事件不包含数据收到通知后主动拉取数据线程模型阻塞EventThread使用独立线程池处理业务逻辑连接状态忽略会话过期监听KeeperState事件Watcher数量注册过多Watcher使用父节点监听代替事件顺序可能延迟但不会乱序依赖ZXID保证顺序权限问题权限不足导致注册失败先添加认证信息永远在process()中重新注册Watcher收到通知后主动拉取数据。

✨ 欢迎来到【Seal ^_^ 的CSDN博客】!✨ 1831

ZooKeeper通知机制深度解析:Watcher的工作原理与实现

Watcher是ZooKeeper提供的一种发布/订阅机制,允许客户端注册对特定ZNode的关注,当该节点发生变化时,服务端会主动通知客户端。fill:#333;important;important;fill:none;color:#333;color:#333;important;fill:none;fill:#333;height:1em;Watcher机制核心1. 注册Watcher2. 存储Watcher3. 触发Watcher4. 发送通知客户端ZooKeeper服务端数据变更。

✨ 欢迎来到【Seal ^_^ 的CSDN博客】!✨ 3294

ZooKeeper 大流量 Watcher 通知处理机制:从原理到优化的全景解析

事件合并是 ZooKeeper 减少不必要通知的关键策略。当同一个节点在短时间内发生多次变化时,ZooKeeper 并不会为每次变化都触发一次通知,而是只触发一次。fill:#333;important;important;fill:none;color:#333;color:#333;important;fill:none;fill:#333;height:1em;有事件合并连续多次变化合并为一次事件一次通知无事件合并时间T1: 节点变化通知客户端1时间T2: 节点变化通知客户端2。

✨ 欢迎来到【Seal ^_^ 的CSDN博客】!✨ 1804
上一篇: [zookeeper] zookeeper系列二:zookeeper持久节点、临时节点及ACL
下一篇: [zookeeper]zookeeper系列四:分布式系统的理解
zkp_java
博客等级 码龄15年 46粉丝 56原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址