加入组

接下来我们实现如何在一个组中注册成员。我们将使用ephemeral znode来创建这些成员节点。那么当客户端程序退出时,这些成员将被删除。

我们创建一个ConnetionWatcher类,然后继承实现一个JoinGroup类:

public class ConnectionWatcher implements Watcher {

 private static final int SESSION_TIMEOUT = 5000;

 protected ZooKeeper zk;

 private CountDownLatch connectedSignal = new CountDownLatch(1);

 public void connect(String hosts) throws IOException, InterruptedException {
     zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
     connectedSignal.await();
 }

 @Override
 public void process(WatchedEvent event) {
     if (event.getState() == KeeperState.SyncConnected) {
         connectedSignal.countDown();
     }
 }

 public void close() throws InterruptedException {
     zk.close();
 }
}
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);
 }
}

加入组与创建组非常相似。我们加入了一个ephemeral znode后,让线程阻塞住。然后我们可以使用命令行查看zookeeper中我们创建的znode。当我们将阻塞的程序强行关闭后,我们会发现我们创建的znode会自动消失。

results matching ""

    No results matching ""