The following is a simple ZooKeeper java application.
Please note that :
1.The watcher registration is aplicable only once ,then in order to get anther notification the program should register again .
2.The program create EPHEMERAL node that is deleted when the connection to ZooKeeper is terminated .
package playwithzookeeper;import java.io.IOException;import java.util.List;import java.util.logging.Level;import java.util.logging.Logger;import org.apache.zookeeper.CreateMode;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooDefs;import org.apache.zookeeper.ZooKeeper;import org.apache.zookeeper.data.ACL;/**
** @author Zvika Peer*/public class PlayWithZookeeper {private static List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;private static ZooKeeper theZooKeeperClient;public static void main(String[] args) throws IOException {try {Watcher myWatcher;myWatcher = new Watcher() {@Overridepublic void process(WatchedEvent we) {String theCreatedPath = we.getPath();System.out.print("The state:" + we.getState() + " The event type " + we.getType() + " The created path:" + theCreatedPath + "\r\n");if ( we.getType() == Event.EventType.NodeDataChanged){byte[] data;try {data = theZooKeeperClient.getData ("/zk_TestPath", null ,null );String decoded = new String(data, "UTF-8");System.out.print("The Data :" + decoded + "\r\n");}catch (Exception ex) {Logger.getLogger(PlayWithZookeeper.class.getName()).log(Level.SEVERE, null, ex);}}}};theZooKeeperClient = new ZooKeeper ("127.0.0.1:2181",4000 , myWatcher);theZooKeeperClient.create("/zk_TestPath", "Hello Zvika".getBytes(), acl, CreateMode.EPHEMERAL );byte[] data = theZooKeeperClient.getData ("/zk_TestPath", myWatcher ,null );theZooKeeperClient.setData("/zk_TestPath" , "Hello Mazal Saadon".getBytes(), 0);theZooKeeperClient.close();} catch (KeeperException ex) {Logger.getLogger(PlayWithZookeeper.class.getName()).log(Level.SEVERE, null, ex);} catch (InterruptedException ex) {Logger.getLogger(PlayWithZookeeper.class.getName()).log(Level.SEVERE, null, ex);}}}
The project structure in NetBeans
אין תגובות:
הוסף רשומת תגובה