1. Purpose
Zookeeper is a distributed service management framework. Zookeeper provides a notification to the client that the client can be notified when a server-side node has been modified or deleted.
2. Server-side deployment
Server-side deployment zookeeper the steps omitted, specific can see my previous article, deployment is relatively simple.
3. The client receives the notification code
import java.io.IOException; import java.util.List; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; class Wa implements Runnable{ Public voidRun () {//connection start K Try{ZooKeeper ZK =NewZooKeeper ("10.218.137.73:2181",500000,NewWatcher () {//Monitor all events that are triggered Public voidProcess (Watchedevent event) {System.out.println ("Changing ..."); } });//Set listenerWatcher WC =NewWatcher () { Public voidProcess (Watchedevent event) {//TODO auto-generated method stub if(Event.gettype () = = eventtype.nodedatachanged) {System.out.println ("Change"); }if(Event.gettype () = = eventtype.nodedeleted) {System.out.println ("Dele"); }if(Event.gettype () = = eventtype.nodecreated) {System.out.println ("Create"); } } };//Polling, where the Exists method is used to inquire about the state, and the listener is set up, and the method in the listener is recalled if it is changed. while(true) {zk.exists ("/jianghuiwen", WC); } }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(Keeperexception e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } }} Public class Main { Public Static voidMain (string[] args) throws IOException, Keeperexception, interruptedexception {//TODO auto-generated method stubThread T =NewThread (NewWa ()); T.start (); }}
Directly paste the code, not add a variety of jar package, if the students to run, you need to set up the relevant jar package, should be log4j and zookeeper package.
4. Testing
Using Zookeeper's own zkcli.sh or modifying nodes with other client modifications to the node, we can see that we have the following output:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Zookeeper Client Settings monitoring