import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.WatchedEvent;
public class ZooKeeperExample implements Watcher {
private ZooKeeper zooKeeper;
public void connect(String host) {
try {
zooKeeper = new ZooKeeper(host, 5000, this);
waitForConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void process(WatchedEvent event) {
if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
System.out.println("Connected to ZooKeeper server");
}
}
public void close() {
try {
zooKeeper.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void waitForConnection() {
while (zooKeeper.getState() != ZooKeeper.States.CONNECTED) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ZooKeeperExample example = new ZooKeeperExample();
example.close();
}
}
try {
String path = "/node";
String data = "Hello, ZooKeeper!";
zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
byte[] responseData = zooKeeper.getData(path, null, null);
String response = new String(responseData);
System.out.println("Data: " + response);
String newData = "Hello, ZooKeeper! Updated.";
zooKeeper.setData(path, newData.getBytes(), -1);
responseData = zooKeeper.getData(path, null, null);
response = new String(responseData);
System.out.println("Updated Data: " + response);
} catch (Exception e) {
e.printStackTrace();
}
public class ZooKeeperWatcher implements Watcher {
private ZooKeeper zooKeeper;
public void connect(String host) {
try {
zooKeeper = new ZooKeeper(host, 5000, this);
waitForConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void process(WatchedEvent event) {
if (event.getType() == Watcher.Event.EventType.NodeDataChanged) {
System.out.println("Node data changed: " + event.getPath());
try {
byte[] responseData = zooKeeper.getData(event.getPath(), null, null);
String response = new String(responseData);
System.out.println("Data: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ZooKeeperWatcher watcher = new ZooKeeperWatcher();
try {
String path = "/node";
String data = "Hello, ZooKeeper!";
watcher.zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
watcher.zooKeeper.getData(path, watcher, null);
String newData = "Hello, ZooKeeper! Updated.";
watcher.zooKeeper.setData(path, newData.getBytes(), -1);
} catch (Exception e) {
e.printStackTrace();
} finally {
watcher.close();
}
}
}