apache-zookeeperznodes

Zookeeper znode watch counter


Having 3 zookeeper in 3 machines with one kafka broker in each zookeeper. number of host : 3 number of znodes to be tracked : 1 [1* number of hosts = 3] Is there any way to track the hostname&znode with Zookeeper.Stat class variables when znode changes its state [caseOk/NoNode]. Trying to implement a counter to track alive znode on multiple host Ports. Straggling at a point to identify first znode exists instance and reconnecting instance.


Solution

  • There's a small ambiguity in your question. I assume that you have 3 separate Zookeeper nodes (standalone or 3 separate ensembles) and want to watch the same ZNode at /some/path in all 3 Zookeeper nodes.

    (If you are referring to a single ensemble with 3 nodes, then you don't have to worry about the nodes as the ensemble will guarantee consistency over the nodes in the ensemble)

    The easiest way is to use Apache Curator recipe (see recipes), NodeCache. Apache Curator is a set of recipes and an extension to the standard ZookeeperClient. It manage all the edge cases and connection states internally so that yo don't have to worry about difficulties in pure Zookeeper client. A NodeCache can watch a given ZNode (at a given ZPath) and notify changes happening to that ZNode.

    See this answer to understand how to initialize a CuratorFramework instance.

    All you have to do is initializing 3 CuratorFramework instances with 3 connection strings (for your 3 nodes) as described in the above answer and then starting the NodeCache objects for each client.

    CuratorFramework client1=//create CuratorFramework intance with corresponding connection string.
    CuratorFramework client2=//create CuratorFramework intance with corresponding connection string.
    CuratorFramework client3=//create CuratorFramework intance with corresponding connection string. 
    

    Then start all of those clients,

    client1.start();
    client2.start();
    client3.start();
    

    Finally, create and start NodeCache instances for the ZNode for each CuratorFramework instance.

    NodeCache znode1=new NodeCache(client1, "/znode/path");
    NodeCache znode2=new NodeCache(client2, "/znode/path");
    NodeCache znode3=new NodeCache(client3, "/znode/path");
    

    Then add NodeCacheListener for each node cache to subscribe for ZNode changes.

    znode1.getListenable().addListener({listener class implementing NodeCacheListener});
    znode2.getListenable().addListener({listener class implementing NodeCacheListener});
    znode3.getListenable().addListener({listener class implementing NodeCacheListener});
    

    Then, start them.

    znode1.start();
    znode2.start();
    znode3.start();
    

    Now, you will receive any change happen through the listeners you registered. Hope you got the idea.