加入组

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

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

  1. public class ConnectionWatcher implements Watcher {
  2. private static final int SESSION_TIMEOUT = 5000;
  3. protected ZooKeeper zk;
  4. private CountDownLatch connectedSignal = new CountDownLatch(1);
  5. public void connect(String hosts) throws IOException, InterruptedException {
  6. zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
  7. connectedSignal.await();
  8. }
  9. @Override
  10. public void process(WatchedEvent event) {
  11. if (event.getState() == KeeperState.SyncConnected) {
  12. connectedSignal.countDown();
  13. }
  14. }
  15. public void close() throws InterruptedException {
  16. zk.close();
  17. }
  18. }
  1. public class JoinGroup extends ConnectionWatcher {
  2. public void join(String groupName, String memberName) throws KeeperException,
  3. InterruptedException {
  4. String path = "/" + groupName + "/" + memberName;
  5. String createdPath = zk.create(path, null/*data*/, Ids.OPEN_ACL_UNSAFE,
  6. CreateMode.EPHEMERAL);
  7. System.out.println("Created " + createdPath);
  8. }
  9. public static void main(String[] args) throws Exception {
  10. JoinGroup joinGroup = new JoinGroup();
  11. joinGroup.connect(args[0]);
  12. joinGroup.join(args[1], args[2]);
  13. // stay alive until process is killed or thread is interrupted
  14. Thread.sleep(Long.MAX_VALUE);
  15. }
  16. }

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