import org.apache.zookeeper.*;
import java.io.IOException;
public class ZooKeeperExample {
private static final String ZOOKEEPER_ADDRESS = "localhost:2181";
private static final int SESSION_TIMEOUT = 3000;
public static void main(String[] args) {
try {
ZooKeeper zooKeeper = new ZooKeeper(ZOOKEEPER_ADDRESS, SESSION_TIMEOUT, null);
String path = "/myconfig";
byte[] data = "hello".getBytes();
CreateMode createMode = CreateMode.PERSISTENT;
zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, createMode);
byte[] readData = zooKeeper.getData(path, false, null);
System.out.println("Data: " + new String(readData));
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeDataChanged) {
try {
byte[] newData = zooKeeper.getData(path, false, null);
System.out.println("Data changed: " + new String(newData));
e.printStackTrace();
}
}
}
};
zooKeeper.exists(path, watcher);
byte[] newData = "world".getBytes();
zooKeeper.setData(path, newData, -1);
zooKeeper.close();
e.printStackTrace();
}
}
}