Database Reference
In-Depth Information
The return value of the create() method is the path that was created by ZooKeeper.
We use it to print a message that the path was successfully created. We will see how the
path returned by create() may differ from the one passed into the method when we
look at sequential znodes.
To see the program in action, we need to have ZooKeeper running on the local machine,
and then we can use the following:
% export CLASSPATH=ch21-zk/target/classes/:$ZOOKEEPER_HOME/*:\
$ZOOKEEPER_HOME/lib/*:$ZOOKEEPER_HOME/conf
% java CreateGroup localhost zoo
Created /zoo
Joining a Group
The next part of the application is a program to register a member in a group. Each mem-
ber will run as a program and join a group. When the program exits, it should be removed
from the group, which we can do by creating an ephemeral znode that represents it in the
ZooKeeper namespace.
The JoinGroup program implements this idea, and its listing is in Example 21-2 . The
logic for creating and connecting to a ZooKeeper instance has been refactored into a
base class, ConnectionWatcher , and appears in Example 21-3 .
Example 21-2. A program that joins a group
public class JoinGroup extends ConnectionWatcher {
public void join ( String groupName , String memberName ) throws
KeeperException ,
InterruptedException {
String path = "/" + groupName + "/" + memberName ;
String createdPath = zk . create ( path , null /*data*/ ,
Ids . OPEN_ACL_UNSAFE ,
CreateMode . EPHEMERAL );
System . out . println ( "Created " + createdPath );
}
public static void main ( String [] args ) throws Exception {
JoinGroup joinGroup = new JoinGroup ();
joinGroup . connect ( args [ 0 ]);
joinGroup . join ( args [ 1 ], args [ 2 ]);
// stay alive until process is killed or thread is interrupted
Thread . sleep ( Long . MAX_VALUE );
Search WWH ::




Custom Search