import org.apache.zookeeper.*;
import java.util.List;
public class Main {
public static void main(String[] args) {
//初始化log4j,zookeeper否则报错。
org.apache.log4j.BasicConfigurator.configure();
try {
Main m = new Main("");
} catch (Exception e) {
e.printStackTrace();
}
}
public Main(String arg){
try {
test();
} catch (Exception e) {
e.printStackTrace();
}
}
private ZooKeeper mZooKeeper;
private void test() throws Exception{
String ip = "localhost";
String addrs = ip + ":2181," + ip + ":2182," + ip + ":2183";
//连接zookeeper服务器。
//addrs是一批地址,如果其中某一个服务器挂掉,其他仍可用。
mZooKeeper = new ZooKeeper(addrs, 300 * 1000, new MyWatcher());
synchronized (Main.class) {
System.out.println("处理...");
Main.class.wait();
}
}
private class MyWatcher implements Watcher {
@Override
public void process(WatchedEvent event) {
byte[] data =null;
try {
data = mZooKeeper.getData("/test_data", true, null);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("类型:" + event.getType());
System.out.println("路径:" + event.getPath());
if(data!=null)
System.out.println("数据修改:" + new String(data));
if (mZooKeeper.getState() == ZooKeeper.States.CONNECTED) {
System.out.println("状态:ZooKeeper.States.CONNECTED");
}
if (event.getState() == Event.KeeperState.SyncConnected) {
System.out.println("状态:Event.KeeperState.SyncConnected");
}
}
}
}
此时,若在监听的节点/test_data通过set命令更新数据
Java程序代码输出:
类型:NodeDataChanged
路径:/test_data
数据修改:hello.world!
状态:ZooKeeper.States.CONNECTED