Reprinted from: http://www.cnblogs.com/sunddenly/p/4031881.html
1.API
2.API Example
Group member relationship in zookeeper
One way to understand zookeeper is to think of it as a highly available file system. However, the file system does not have files and directories, but uses the concept of "node", called Znode. Znode can be used either as a container to hold data (as a file) or as a container to hold other Znode (like a directory). All Znode constitute a hierarchical namespace. A natural way to set up a group membership list is to use this hierarchy to create a znode as a parent node named after the group name, and then create the Znode as a child node with the group member name (server name) as the nodes. For example, a set of znode with hierarchical structure is given.
To create a group sample code:
Package Org.zk;import Java.io.ioexception;import java.util.concurrent.countdownlatch;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.keeperstate;import Org.apache.zookeeper.zoodefs.ids;import Org.apache.zookeeper.zookeeper;public class CreateGroup implements watcher{private static finalintsession_timeout=5000; Private ZooKeeper ZK; Private Countdownlatch connectedsignal=NewCountdownlatch (1); @Override Publicvoidprocess (Watchedevent event) {if(event.getstate () = =keeperstate.syncconnected) {Connectedsignal.countdown (); }} public staticvoidMain (string[] args) throws IOException, Interruptedexception, keeperexception {creategroup CreateGroup=NewCreateGroup (); Creategroup.connect (args[0]); Creategroup.create (args[1]); Creategroup.close (); } PrivatevoidClose () throws Interruptedexception {zk.close (); } PrivatevoidCreate (String groupName) throws Keeperexception, interruptedexception {string path="/"+GroupName; if(Zk.exists (Path,false)==NULL) {zk.create (path,NULL/*Data*/, Ids.open_acl_unsafe, createmode.persistent); } System.out.println ("Created:" +path); } PrivatevoidConnect (String hosts) throws IOException, interruptedexception {ZK=NewZooKeeper (Hosts, Session_timeout, This); Connectedsignal.await (); }}
Code Analysis
In the above code, when the main () method executes, an instance of CreateGroup is created and the Connect () method of the instance is called. The Connect method instantiates an object of the new zookeeper class, which is the primary class in the client API and is responsible for maintaining the connection between the client and the Zookeeper service. The constructor for the zookeeper class has three parameters:
The first is: the host address of the Zookeeper service, which specifies the port, and the default port is 2181.
The second one is: the session timeout parameter in milliseconds, where we set it to 5 seconds.
The third is: The argument is an instance of a Watcher object.
The Watcher object receives callbacks from the zookeeper to get notifications for various events. In this example, CreateGroup is a Watcher object, so we pass it to the zookeeper constructor.
When an instance of zookeeper is created, a line thread attached is initiated to the Zookeeper service. Since the call to the constructor is returned immediately, be sure to wait for the connection between the new Zookeeper object and the zookeeper service to succeed before using it. We use the Java Countdownlatch class to block the use of the newly created Zookeeper object until the Zookeeper object is ready. This is the Watcher class.
Use, there is only one method in its interface:
public void process (Watcherevent event);
After the client has established a connection with zookeeper, the Watcher process () method is called, and the parameter is an event that represents the connection. When a connection event is received (represented by the enumeration value syncconnected of Watcher.Event.KeeperState), we decrement its counter by calling the Countdownlatch's Countdown () method. The latch (latch) is created with a counter with a value of 1 that represents the number of events that need to occur before it frees all waiting threads. After calling the countdown () method, the value of the counter changes to 0, and the await () method returns.
Now the Connect () method has returned, and the next execution is the CreateGroup create () method. In this method, we use the Create () method in the zookeeper instance to make a new zookeeper Znode. The required parameters are:
Path: represented by a string.
Znode: An array of bytes, with null values in this example.
Access Control List: referred to as ACL, this example uses a fully open ACL that allows any client to read and write to Znode.
Create the type of Znode: There are two types of znode: ephemeral and persistent.
When a client that creates a znode disconnects, the ephemeral znode is removed by the zookeeper service, regardless of whether the client is explicitly disconnected or is terminated for any reason. In contrast, persistent znode are not removed when the client disconnects. We want Znode that represent a group to survive longer than the lifetime of the creation program, so in this case we have created a persistent znode.
The return value of the Create () method is the path created by zookeeper, and we use this return value to print a message indicating that the path was successfully created. When we look at "Order Znode" (Sequential Znode). You will find that the path returned by the Create () method differs from the path passed to the method.
Join Group
Package Org.zk;import Java.io.ioexception;import org.apache.zookeeper.createmode;import Org.apache.zookeeper.keeperexception;import Org.apache.zookeeper.zoodefs.ids;public class JoinGroup extends connectionwatcher{ PublicvoidJoin (String groupname,string membername) throws Keeperexception, interruptedexception{string path= "/" +groupname+ "/" +membername; String Createdpath=zk.create (Path,NULL, Ids.open_acl_unsafe, createmode.ephemeral); System.out.println ("Created:" +Createdpath); } public staticvoidMain (string[] args) throws Interruptedexception, IOException, keeperexception {joingroup joingroup=NewJoingroup (); Joingroup.connect (args[0]); Joingroup.join (args[1], args[2]); //stay alive until process is killed or thread is interruptedThread.Sleep (Long.max_value); }}
List Group members
Package Org.zk;import java.io.ioexception;import java.util.list;import org.apache.zookeeper.KeeperException; Import Org.apache.zookeeper.zookeeper;public class Listgroup extends Connectionwatcher { publicvoidlist (String groupnmae) throws Keeperexception, interruptedexception{string path="/"+Groupnmae; Try{List<String> children = Zk.getchildren (path,false); if(Children.isempty ()) {System.out.printf ("No memebers in Group%s\n", Groupnmae); System.exit (1); } for(String child:children) {System.out.println (child); } } Catch(keeperexception.nonodeexception e) {System.out.printf ("Group%s does not exist \ n", Groupnmae); System.exit (1); }} public staticvoidMain (string[] args) throws IOException, Interruptedexception, keeperexception {listgroup listgroup=NewListgroup (); Listgroup.connect (args[0]); Listgroup.list (args[1]); Listgroup.close (); }}Delete a group
Let's see how to delete a group. The Zookeeper class provides a delete () method with two parameters:
1. Path
2. Version number
If the version number provided matches the version number of Znode, zookeeper will delete the Znode. This is an optimistic locking mechanism that allows the client to detect changes to the Znode. By setting the version number to-1, you can bypass this version detection mechanism and delete it directly, regardless of the Znode version number. Zookeeper does not support recursive deletions, so the child nodes must be deleted before the parent node is deleted.
In code 3.5, the DeleteGroup class is used to delete a group and all its members.
Code 3.5 program to delete a group and all its members
Package Org.zk;import java.io.ioexception;import java.util.list;import org.apache.zookeeper.KeeperException; public class DeleteGroup extends connectionwatcher{ publicvoid Delete(String groupName) throws Interruptedexception, keeperexception{string path="/"+GroupName; List<String>children; Try{Children= Zk.getchildren (Path,false); for(String child:children) {ZK.Delete(path+ "/" +child,-1); } ZK.Delete(Path, 1);//delete parent node itself}Catch(keeperexception.nonodeexception e) {System.out.printf ("Group%s does not exist\n", GroupName); System.exit (1); }} public staticvoidMain (string[] args) throws Interruptedexception, IOException, keeperexception {deletegroup deletegroup=NewDeleteGroup (); Deletegroup.connect (args[0]); DeleteGroup.Delete(args[1]); Deletegroup.close (); }}
Simple use of the Zookeeper API (reprint)