Zookeeper how to monitor permanently

Source: Internet
Author: User
Tags zookeeper

Transferred from: http://www.cnblogs.com/viviman/archive/2013/03/11/2954118.html

basic knowledge of a back adjustment

Znode can be monitored, including changes in the data stored in this directory node, changes in sub-node directories, and so on, once the change can notify the settings monitoring client, this function is zookeeper for the application of the most important features, through this feature can be achieved by the functions of the centralized management of the configuration, cluster management, Distributed locks and so on.

Create a zookeeper instance, the first parameter is the destination server address and port, the second parameter is the session time-out time, the third is the callback method when the node changes
ZooKeeper ZK = new ZooKeeper ("127.0.0.1:2181", 500000,new Watcher () {
Monitor all events that are triggered
public void process (Watchedevent event) {
DoSomething
}

});
Configure all the configuration of APP1 to/app1 Znode, APP1 all the machines to monitor the/APP1 node (zk.exist ("/app1", true) and implement the callback method watcher, zookeeper on/APP1 Znode node, when the data changes, each machine will be notified, the Watcher method will be executed, then the application can then remove the data (Zk.getdata ("/app1", False,null));

The following table lists the correspondence between write operations and the events generated within ZK:

Event for "/path"

Event for "/path/child"

Create ("/path")

eventtype.nodecreated

NA

Delete ("/path")

eventtype.nodedeleted

NA

SetData ("/path")

Eventtype.nodedatachanged

NA

Create ("/path/child")

Eventtype.nodechildrenchanged

eventtype.nodecreated

Delete ("/path/child")

Eventtype.nodechildrenchanged

eventtype.nodedeleted

SetData ("/path/child")

NA

Eventtype.nodedatachanged

The correspondence between the write events in ZK and the triggered watcher is as follows:

Event for "/path"

Defaultwatcher

Exists
("/path")

GetData
("/path")

GetChildren
("/path")

Eventtype.none

eventtype.nodecreated

eventtype.nodedeleted

√ (not normal)

Eventtype.nodedatachanged

Eventtype.nodechildrenchanged

Combining the above two tables, we can summarize what watcher can be triggered by various write operations, as shown in the following table:

"/path"

"/path/child"

Exists

GetData

GetChildren

Exists

GetData

GetChildren

Create ("/path")

Delete ("/path")

SetData ("/path")

Create ("/path/child")

Delete ("/path/child")

SetData ("/path/child")

If session close, Authfail, and invalid occur, then all types of wather will be triggered

Zkclient In addition to some convenient packaging, the use of watcher has made a little enhancement. For example, Subscribechildchanges is actually focusing on two events through exists and GetChildren. When Create ("/path"), the listener registered with GetChildren on the path will also be called. In addition, Subscribedatachanges actually registered the event only through exists. As you can see from the previous table, for an update, the watcher registered with exists and GetData will either be triggered or will not be triggered.

Getdata,getchildren (), exists () these three methods can be set for the path in the parameter watcher, when the corresponding node of path corresponding change, the server side will give the corresponding set of watcher client Sends a one-time trigger notification event. After receiving this trigger notification event, the client can process it accordingly according to its own business logic.

Note that this watcher function is a one-time, if you want to continue to get watcher notice, after processing the event, to re-register.

Second test watcher callback mechanism

Watcher Instances

Watcher WH = new Watcher () {

public void process (Watchedevent event) {

System.out.println ("Callback Watcher Instance: path" + event.getpath () + "type:"

+ Event.gettype ());

}

};

ZooKeeper ZK = new ZooKeeper ("10.15.82.166:3351", 500000, WH);

System.out.println ("---------------------");

Create a node root, the data is MyData, do not have ACL permission control, the node is permanent (that is, the client shutdown will not disappear)

Zk.exists ("/root", true);

Zk.create ("/root", "MyData". GetBytes (), Ids.open_acl_unsafe,

Createmode.persistent);

System.out.println ("---------------------");

Create a Childone znode under root, the data is Childone, do not control ACL permissions, the node is permanent

Zk.exists ("/root/childone", true);

Zk.create ("/root/childone", "Childone". GetBytes (), Ids.open_acl_unsafe,

Createmode.persistent);

System.out.println ("---------------------");

Delete/root/childone This node, the second parameter is version, 1 words are deleted directly, ignoring version

Zk.exists ("/root/childone", true);

Zk.delete ("/root/childone",-1);

System.out.println ("---------------------");

Zk.exists ("/root", true);

Zk.delete ("/root",-1);

System.out.println ("---------------------");

Close session

Zk.close ();

---------------------

Callback Watcher instance: path NULL type: None

Callback Watcher instance: path/root type: nodecreated

---------------------

Callback Watcher instance: path/root/childone type: nodecreated

---------------------

Callback Watcher instance: path/root/childone type: nodedeleted

---------------------

Callback Watcher instance: path/root type: nodedeleted

---------------------

Three permanent callbacks

Class 3 event triggering wather no longer function, that is, the so-called (a function), but, how to permanently monitor it? This requires us to control the logic of the program, online there is a better way, but in a simple application, you can again Wather method inside again set monitoring, this method is very stupid, but, very effective, to achieve the desired effect.

Watcher WH = new Watcher () {public void process (Watchedevent event) {Log.ac_debug ("trigger callback Watcher instance: path"            + Event.getpath () + "type:" + event.gettype ());                    if (event.gettype () = = Eventtype.none) {try {/////To determine if Userauth permissions can be accessed UserPath                    String Auth_type = "Digest";                    Zk.addauthinfo (Auth_type, Userauth.getbytes ());                Zk.getdata (UserPath, NULL, NULL);                    } catch (Exception e) {//E.printstacktrace (); Log.ac_error ("Get node faild:userpath=" + UserPath + ", auth=" + Userauth + "e:" + e.getmessage                    ());                Return            } log.ac_info ("userpath=" + UserPath + "userauth=" + Userauth); } try {switchinfo = Getallswitch ();//Update the configuration information under UserPath and anonymous user paths, listen for these nodes//listen to the User path section Point Log.ac_debug ("LesSon user= "+ UserPath +" node ... "); Zk.exists (UserPath, true);                Listen for anonymous User path node Log.ac_debug ("Lesson user=" + Anonymoususerpath + "node ...");                Zk.exists (Anonymoususerpath, true); Listen for the switch node under User path if (zk.exists (UserPath, false) = null) {log.ac_debug ("Lesson user=" +                    UserPath + "' s Swich node ..."); list<string> swnodes = Zk.getchildren (UserPath, true);                    Monitor switch layer node change iterator<string> IT_SW = Swnodes.iterator ();                        while (It_sw.hasnext ()) {String Swpath = UserPath + "/" + It_sw.next ();                        Log.ac_debug ("Lesson user=" + Swpath + "node ...");                    Zk.exists (Swpath, true);                }}} catch (Exception e) {e.printstacktrace (); Log.ac_error ("Lesson Znode erROR: "+ e.getmessage ()); }        }    };

Zookeeper how to listen permanently

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.