public class CreateGroup implements Watcher { private static final int SESSION_TIMEOUT=5000; //ZooKeeper類是客戶端API的主要類,用於維護客戶端和ZooKeeper服務之間的鏈接 private ZooKeeper zk; //鎖存器(latch)此計數器爲1,表示在釋放全部等待線程以前須要發生的事件數, private CountDownLatch connectedSignal= new CountDownLatch(1); public void connect(String hosts) throws InterruptedException, IOException { //參數this表示一個Watcher對象接收來自於Zookeeper的回調,以得到各類事件的通知,在此表示CreateGroup對象 zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this); connectedSignal.await(); } public void process(WatchedEvent watchedEvent) { // Watcher interface if (watchedEvent.getState()==Event.KeeperState.SyncConnected){ //在調用這個方法表示計數器遞減1,若計數器的值變爲0,則await()方法返回 connectedSignal.countDown(); } } //建立組 public void create(String groupName) throws KeeperException, InterruptedException { String path="/"+groupName; String createPath = zk.create(path, null/*data*/, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);// 持久化的 znode System.out.println("Created "+createPath); } //加入組 public void join(String groupName,String memberName) throws KeeperException, InterruptedException { String path = "/" + groupName + "/" + memberName; String createPath = zk.create(path, null/*data*/, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);// 持久化的 znode System.out.println("Created "+createPath); } //列出組成員 public void ListGroup(String groupName){ String path="/"+groupName; try { List<String> children = zk.getChildren(path, false); if (children.isEmpty()){ System.out.println(String.format("No members in group %s",groupName)); System.exit(1); } for (String child:children){ System.out.println(child); } } catch (KeeperException.NoNodeException e) { System.out.println(String.format("Group %s does not exist\n",groupName)); System.exit(1); } catch (InterruptedException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } } //刪除組成員 public void deleteGroup(String groupName){ String path="/"+groupName; try { List<String> children = zk.getChildren(path, false); for (String child:children){ //節點路徑和版本號 將版本號設置爲-1 能夠繞過版本檢測機制 zk.delete(path+"/"+child,-1); } zk.delete(path,-1); } catch (KeeperException.NoNodeException e) { System.out.println(String.format("Group %s does not exist\n",groupName)); System.exit(1); } catch (InterruptedException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } } public void close() throws InterruptedException { zk.close(); } public static void main(String[] args) throws IOException, InterruptedException, KeeperException { CreateGroup createGroup = new CreateGroup(); createGroup.connect("192.168.1.132:2181"); //createGroup.join("a","b"); //createGroup.ListGroup("a"); createGroup.deleteGroup("a"); createGroup.close(); } }