Zookeeper Watcher API description, zookeeperwatcher

Source: Internet
Author: User
Tags zookeeper client

Zookeeper Watcher API description, zookeeperwatcher

Watcher is a core function in ZooKeeper. Watcher can monitor data changes of directory nodes and subdirectory changes. Once these statuses change, the server will notify all Watcher sets on this directory node, so that every client will soon know that the status of the directory node it is interested in has changed, and then respond accordingly.

You can set the observed operations: exists, getChildren, getData

Operations that can trigger observation: create, delete, setData

When znode changes in some way, the "watch" mechanism can notify the client. you can set the observation for the "operation" of the ZooKeeper service. Other operations of the service can trigger the observation.

For example, the client can call the exists operation on a client and set an observation on it. If the znode does not exist at this time, exists returns false, if this znode is created by another client, this observation will be triggered and the previous client will be notified.

Description: The operations performed by the zookeeper client on the server cannot be rolled back.
It means that every time the zk client communicates with the server, it will remember the latest zxid on the server. If the client and server are disconnected at a certain time point, the next time you re-connect to the machine in the cluster, the system checks whether the server currently connected has the same zxid as the client, or the zxid has been updated. Once the client finds that the zxid of the server is smaller than itself, the client will disconnect from the server and reconnect to other servers in the cluster.

1. Link to the Zookeeper Server

/*** <P> connect to Zookeeper </p> * <pre> * [connectString server address configuration] * Format: 192.168.1.1: 2181,192.168 .1.2: 2181,192.168 .1.3: 2181 * This address is configured with multiple ip addresses: ports are separated by commas. The underlying operation * ConnectStringParser connectStringParser = new ConnectStringParser ("192.168.1.1: 2181,192.168 .1.2: 2181,192.168 .1.3: 2181 "); * This class is mainly used to parse the input address list string and save the other strings in an ArrayList. * ArrayList <InetSocketAddress> serverAddresses = new ArrayList <InetSocketAddress> (); * next, This address list will be further encapsulated into a StaticHostProvider object, and this object will be maintained throughout the operation. * The ZK client stores all servers in a List and randomly disconnects them (this random process is one-time) and forms a ring, it is used one by one from bits 0. * Therefore, the Server address can be configured repeatedly to make up for the defect that the client cannot set the Server weight, but it also increases the risk. ** [Client-server Session description] * In ZooKeeper, after a connection is established between the client and the server, the Session is established and a globally unique Session ID (Session ID) is generated ). * A persistent connection is maintained between the server and the client. During the SESSION_TIMEOUT period, the server determines whether the client is connected normally (the client regularly sends heart_beat to the server, and the server resets the next SESSION_TIMEOUT time ). * Under normal circumstances, the Session is always valid and the Session information is saved on all machines in the ZK cluster. * In the case of network or other problems (for example, the ZK machine connected by the client is down or the network is disconnected for other reasons ), the connection between the client and the server currently connected is broken. * at this time, the client will take the initiative to enter the connectString parameter of the constructor when instantiating the ZK object) select a new address to connect. ** [Session time] * the client does not allow you to set the session time-out time at will. On the ZK server, the session time-out time is limited, it is mainly set by minSessionTimeout and maxSessionTimeout parameters. * If the timeout time set by the client is not in this range, it will be set to the maximum or minimum time. The default Session timeout value is 2 * tickTime ~ 20 * tickTime * </pre> * @ param connectString Zookeeper service address * @ param sessionTimeout Zookeeper connection timeout */public void connectionZookeeper (String connectString, int sessionTimeout) {this. releaseConnection (); try {// ZK client allows us to set all ZK server addresses here zk = new ZooKeeper (connectString, sessionTimeout, this); // use CountDownLatch. the await () thread (current thread) is blocked until all other threads with CountDownLatch have completed execution (countDown () results in 0) connectedSemaphore. await ();} catch (InterruptedException e) {LOG. error ("connection creation failed, InterruptedException, e" + e. getMessage (), e);} catch (IOException e) {LOG. error ("connection creation failed, IOException, e" + e. getMessage (), e );}}

 

2. Create a node

/*** <P> create zNode, String create (path <Node path>, data [] <node content>, List (ACL access control List ), createMode <zNode creation type>) </p> <br/> * <pre> * node creation type (CreateMode) * 1. PERSISTENT: persistence node * 2. PERSISTENT_SEQUENTIAL: the persistence node is automatically numbered sequentially. This node will automatically add 1*3 and EPHEMERAL based on the number of existing nodes: Temporary node client, when the session times out, these nodes will be automatically deleted. * 4. EPHEMERAL_SEQUENTIAL: temporarily auto-numbered node * </pre> * @ param path zNode Node path * @ param data zNode data content * @ return returns true if creation is successful, and false if creation is successful. */public bool Ean createPath (String path, String data) {try {String zkPath = this. zk. create (path, data. getBytes (), ZooDefs. ids. OPEN_ACL_UNSAFE, CreateMode. PERSISTENT); LOG.info ("Node created successfully, Path:" + zkPath + ", content:" + data); return true;} catch (KeeperException e) {LOG. error ("failed to create node, KeeperException! Path: "+ path +", data: "+ data +", errMsg: "+ e. getMessage (), e);} catch (InterruptedException e) {LOG. error ("Node creation failed, InterruptedException! Path: "+ path +", data: "+ data +", errMsg: "+ e. getMessage (), e);} return false ;}

3. delete a node

/*** <P> delete a zMode node, void delete (path <Node path>, stat <data version>) </p> <br/> * <pre> * Note * 1. The version number is inconsistent and cannot be deleted. * 2. if the version number is different from the version number of znode, it cannot be deleted. It is an Optimistic Locking Mechanism. if the version number is set to-1, the version is not checked and deleted directly. * </pre> * @ param path zNode Node path * @ return returns true If deletion is successful, and false if deletion is successful. */public boolean deletePath (String path) {try {this. zk. delete (path,-1); LOG.info ("Node deleted successfully, Path:" + path); return true;} catch (KeeperException e) {LOG. error ( "Failed to delete the node. KeeperException occurred! Path: "+ path +", errMsg: "+ e. getMessage (), e);} catch (InterruptedException e) {LOG. error (" failed to delete node, InterruptedException! Path: "+ path +", errMsg: "+ e. getMessage (), e);} return false ;}

4. Assignment of nodes/updating of nodes

/*** <P> update the data content of the specified node, Stat setData (path <Node path>, data [] <node content>, stat <data version>) </p> * <pre> * if data on a znode is set to-1, skip version check * </pre> * @ param path zNode Node path * @ param data zNode data content * @ return returns true if the update is successful, returns false */public boolean writeData (String path, String data) {try {Stat stat = this. zk. setData (path, data. getBytes (),-1); LOG.info ("data updated successfully, path:" + path + ", stat:" + stat); return true;} catch (Kee PerException e) {LOG. error ("failed to update data, KeeperException! Path: "+ path +", data: "+ data +", errMsg: "+ e. getMessage (), e);} catch (InterruptedException e) {LOG. error ("failed to update data, InterruptedException! Path: "+ path +", data: "+ data +", errMsg: "+ e. getMessage (), e);} return false ;}

5. Read node values

/*** <P> read data from the specified node, byte [] getData (path <Node path>, watcher <monitor>, stat <data version>) </p> * @ param path zNode Node path * @ return value of the node storage; return value; return null if no value */public String readData (String path) {String data = null; try {data = new String (this. zk. getData (path, false, null); LOG.info ("data read succeeded, path:" + path + ", content:" + data);} catch (KeeperException e) {LOG. error ("failed to read data, KeeperException! Path: "+ path +", errMsg: "+ e. getMessage (), e);} catch (InterruptedException e) {LOG. error (" failed to read data, InterruptedException! Path: "+ path +", errMsg: "+ e. getMessage (), e);} return data ;}

6. Determine whether a node exists

/*** <P> checks whether a zNode exists. Stat exists (path <Node path>, watch <and sets whether to monitor this directory node, here, watcher is the watcher specified when the ZooKeeper instance is created>) </p> * @ param path zNode Node path * @ return returns true, otherwise, false */public boolean isExists (String path) {try {Stat stat = this. zk. exists (path, false); return null! = Stat;} catch (KeeperException e) {LOG. error ("failed to read data, KeeperException! Path: "+ path +", errMsg: "+ e. getMessage (), e);} catch (InterruptedException e) {LOG. error (" failed to read data, InterruptedException! Path: "+ path +", errMsg: "+ e. getMessage (), e);} return false ;}

7. Obtain subnodes under a node

/*** <P> get all the subnodes under a node, List getChildren (path <Node path>, watcher <monitor>) this method has multiple overloading </p> * @ param path zNode Node path * @ return sub-node path set description. The value returned here is the node name * <pre> * eg. */node/child1 */node/child2 * getChild ("node") the value in the collection is ["child1 ", "child2"] * </pre> ***** @ throws KeeperException * @ throws InterruptedException */public List <String> getChild (String path) {try {List <String> list = this. zk. getChildren (pat H, false); if (list. isEmpty () {LOG.info ("no node in" + path);} return list;} catch (KeeperException e) {LOG. error ("failed to read the data of the subnode. KeeperException! Path: "+ path +", errMsg: "+ e. getMessage (), e);} catch (InterruptedException e) {LOG. error ("failed to read the data of the subnode, InterruptedException! Path: "+ path +", errMsg: "+ e. getMessage (), e);} return null ;}

8. Release links

/*** Close the ZK connection */public void releaseConnection () {if (null! = Zk) {try {this. zk. close ();} catch (InterruptedException e) {LOG. error ("release connection error," + e. getMessage (), e );}}}


For more information, see [http://www.cnblogs.com/dennisit/p/4340688.html].

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.