Watcher's Demo

Source: Internet
Author: User
Tags define session sleep zookeeper
/**
* Classname:zookeeperwatcher
* This class is a watcher class
* date:2017 August 31 9:44:31
* @author Yanlong
*/
public class Zookeeperwatcher implements watcher{

Defining Atomic Variables
Atomicinteger seq = new Atomicinteger ();
Define session Expiration Time
private static final int session_timeout = 1000;
Zookeeper Server address
private static final String connection_addr = "112.124.121.34:2181";
ZK Parent Path Settings
private static final String Parent_path = "/P";
ZK Sub-path settings
private static final String Children_path = "/P/C";
Enter logo
private static final String Log_prefix_of_main = "" MAIN "";
ZK variable
Private ZooKeeper ZK = null;
Semaphore settings are used to wait for the zookeeper connection to notify the blocker to continue down.
Private Countdownlatch Connectedsemaphore = new Countdownlatch (1);


/**
*
* CreateConnection: Create ZK connection
* @author Yanlong
* date:2017 August 31 10:09:16
* @param connectaddr ZK server address List
* @param sessiontimeout Session timeout period
*/
public void CreateConnection (String connectaddr,int sessiontimeout) {
This.releaseconnection ();
try {
ZK = new ZooKeeper (connectaddr, sessiontimeout, this);
System.out.println (log_prefix_of_main+ "Start connection to ZK server");
Connectedsemaphore.await ();
} catch (Exception e) {
E.printstacktrace ();
}
}

/**
* Close Connection
* Releaseconnection:
* @author Yanlong
* date:2017 August 31 10:10:37
*/
public void Releaseconnection () {
if (THIS.ZK! = null) {
try{
This.zk.close ();
}catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}

/**
*
* Createpath: Create node
* @author Yanlong
* date:2017 August 31 10:14:58
* @param Path of path node
* @param data node content
* @return
*/
public boolean Createpath (String path,string Data,boolean needwatch) {
Set up monitoring (since zookeeper monitoring is all-in-one, you must set up monitoring every time)
try {
This.zk.exists (path, needwatch);//pre-monitoring before creating a node
System.out.println (log_prefix_of_main+ "node creation succeeded, Path:" +
This.zk.create (
/** Path **/
Path
/** Data **/
Data.getbytes (),
/** all visible **/
Ids.open_acl_unsafe,
/** Permanent Storage **/
Createmode.persistent) + ", Content:" +data);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
return false;
}
return true;
}

/**
*
* ReadData: Reads the contents of the specified node data
* @author Yanlong
* date:2017 August 31 10:32:09
* @param Path of path node
* @param needwatch
* @return
*/
public string ReadData (string Path,boolean needwatch) {
try {
SYSTEM.OUT.PRINTLN ("read operation ...");
return new String (This.zk.getData (path, needwatch, null));
} catch (Exception e) {
E.printstacktrace ();
Return "";
}
}

/**
*
* WriteData: Update the data content of the specified node
* @author Yanlong
* date:2017 August 31 10:34:55
* @param Path of path node
* @param data content
* @return
*/
public boolean writedata (String path,string data) {
try {
SYSTEM.OUT.PRINTLN (log_prefix_of_main+ "Update data succeeded, path:" +path+ ", stat:" +
This.zk.setData (Path, data.getbytes (),-1));
} catch (Exception e) {
E.printstacktrace ();
}
return false;
}

/**
* Delete the specified node
* Deletenode:
* @author Yanlong
* date:2017 August 31 10:38:29
* @param Path of path node
*/
public void Deletenode (String path) {
try {
This.zk.delete (Path,-1);
System.out.println (log_prefix_of_main+ "Delete node succeeded, path:" +path);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

/**
*
* Exists: Determine if the node exists
* @author Yanlong
* date:2017 August 31 10:40:57
* @param Path of path node
* @param needwatch
* @return
*/
Public Stat exists (String Path,boolean needwatch) {
try {
return this.zk.exists (path, needwatch);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
return null;
}
}

/**
*
* GetChildren: Get child nodes
* @author Yanlong
* date:2017 August 31 10:44:27
* @param path
* @param needwatch
* @return
*/
Private list<string> GetChildren (String Path,boolean needwatch) {
try {
return This.zk.getChildren (path, needwatch);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
return null;
}
}

/**
*
* Deletealltestpath: Delete all nodes
* @author Yanlong
* date:2017 August 31 10:50:58
*/
public void Deletealltestpath (Boolean needwatch) {
if (This.exists (Children_path, needwatch)! = null) {
This.deletenode (Children_path);
}
if (This.exists (Parent_path, needwatch)! = null) {
This.deletenode (Parent_path);
}
}

/**
*
* TODO Delete all nodes
* @see org.apache.zookeeper.watcher#process (org.apache.zookeeper.WatchedEvent)
*/
@Override
public void process (Watchedevent event) {
System.out.println ("Enter process ... event =" +event);

try {
Thread.Sleep (200);
} catch (Interruptedexception e) {
E.printstacktrace ();
}

if (event = = null) {
Return
}

Connection Status
Keeperstate keeperstate = Event.getstate ();
Event Type
EventType EventType = Event.gettype ();
The affected path
String path = Event.getpath ();

String Logprefix = "watcher-" +this.seq.incrementandget () + "" ";

System.out.println (logprefix+ "received watcher notice");
System.out.println (logprefix+ "Connection Status" +keeperstate.tostring ());
System.out.println (logprefix+ "Event Type" +eventtype.tostring ());

if (keeperstate.syncconnected = = keeperstate) {
Successfully connected to the ZK server
if (Eventtype.none = = EventType) {
System.out.println (logprefix+ "Successfully connected to the ZK server");
Connectedsemaphore.countdown ();
}
Create a Node
else if (eventtype.nodecreated = = EventType) {
System.out.println (logprefix+ "node creation");
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
This.exists (path, true);
}
Update node
else if (eventtype.nodedatachanged = = EventType) {
System.out.println (logprefix+ "node Data Update");
try {
Thread.Sleep (100);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println (logprefix+ "Data content:" +this.readdata (Parent_path, true));
}
Update child nodes
else if (eventtype.nodechildrenchanged = = EventType) {
System.out.println (logprefix+ "Sub-node Change");
try {
Thread.Sleep (3000);
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
System.out.println (logprefix+ "Sub-node List" +this.getchildren (Parent_path, true));
}
Delete a node
else if (eventtype.nodedeleted = = EventType) {
System.out.println (logprefix+ "node" +path+ "deleted");
}
}else if (keeperstate.disconnected = = keeperstate) {
System.out.println (logprefix+ "Disconnected from ZK server");
}else if (keeperstate.authfailed = = keeperstate) {
System.out.println (logprefix+ "permission check failed");
}else if (keeperstate.expired = = keeperstate) {
System.out.println (logprefix+ "Session invalidation");
}

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

}

/**
* Test Zookeeper Monitoring
* Test Watcher function
* Main:
* @author Yanlong
* date:2017 August 31 11:20:43
* @param args
* @throws Exception
*/
public static void Main (string[] args) throws Exception {
Establish watcher
Zookeeperwatcher zkwatcher = new Zookeeperwatcher ();
Create a connection
Zkwatcher.createconnection (CONNECTION_ADDR, session_timeout);

Thread.Sleep (1000);

Cleanup node
Zkwatcher.deletealltestpath (FALSE);

if (Zkwatcher.createpath (Parent_path, System.currenttimemillis () + "", true)) {//Set whether you need to listen
Thread.Sleep (1000);

Reading data
SYSTEM.OUT.PRINTLN ("--------Read parent-----------");
Zkwatcher.readdata (Parent_path, true);

Read child nodes
SYSTEM.OUT.PRINTLN ("--------Read children path-----------");
Zkwatcher.getchildren (Parent_path, false);

Update data
Zkwatcher.writedata (Parent_path, System.currenttimemillis () + "");
//
Thread.Sleep (1000);



Create child nodes
Zkwatcher.createpath (Children_path, System.currenttimemillis () + "", true);
Zkwatcher.createpath (children_path+ "/c1", System.currenttimemillis () + "", true);
Zkwatcher.createpath (children_path+ "/c1/c2", System.currenttimemillis () + "", true);


Thread.Sleep (1000);
//
Zkwatcher.writedata (Children_path, System.currenttimemillis () + "");


}

Thread.Sleep (50000);
Cleanup node
Zkwatcher.deletealltestpath ();
Thread.Sleep (1000);
Zkwatcher.releaseconnection ();

}


}

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.