最初にすべてのマシンの動物園管理サービスを開始します
クライアント側
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.List;
public class zkClient {
private static ZooKeeper zk = null;
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
int sessionTimeout = 4000;
zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
}
});
registerListener();
Thread.sleep(Long.MAX_VALUE);
}
public static void registerListener() throws KeeperException, InterruptedException {
lic void test2() throws KeeperException, InterruptedException {
List<String> children = zk.getChildren("/parent", new Watcher() {
public void process(WatchedEvent event) {
try {
registerListener();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
for (String node : children) {
System.out.println(node);
}
}
}
サーバ側
package com.atguigu.online;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
public class zkServer {
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
int sessionTimeout = 4000;
ZooKeeper zk = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
public void process(WatchedEvent event) {
}
});
Stat exists = zk.exists("/parent", false);
if (exists == null){
zk.create("/parent", "".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.create("/parent/" + args[0], args[1].getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
Thread.sleep(Long.MAX_VALUE);
}
}