package zookeeper;
import java.util.List;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
/**
* 众所周知,ZooKeeper中的ZNode是树形结构, 现在我需要给/app1结点设置watcher,监听/app1下增减、删除和修改的结点,
* 并将相应的事件使用log4j记录到日志文件中。ZNode的变化可以直接通过event.getType来获取 使用zk.exists(PATH,
* wc);来为PATH结点设置watcher,所有结点都可以使用wc做watcher。
*
* @author 小明 2015.5.23
*/
public class WatchClient implements Runnable {
//
private List<String> nodeList;
private static final String path = "/app";
private static ZooKeeper zk;
public static void main(String[] args) throws Exception {
WatchClient client = new WatchClient();
Thread thread = new Thread(client);
thread.start();
}
public WatchClient() throws Exception {
zk = new ZooKeeper("192.168.1.97:2181", 99999, new Watcher() {
public void process(WatchedEvent event) {
System.out.println(event.getPath() + event.getType());
}
});
}
/**
* 设置watch线程
*/
public void run() {
Watcher watcher = new Watcher() {
public void process(WatchedEvent event) {
//System.out.println("__________");
// 结点数据改变前的节点列表
List<String> nodeListBefore = nodeList;
// 主结点的数据发生改变时
if (event.getType() == EventType.NodeDataChanged) {
System.out.println("Node data changed:" + event.getPath());
}
if (event.getType() == EventType.NodeDeleted) {
System.out.println("Node data deleted:" + event.getPath());
}
if (event.getType() == EventType.NodeCreated) {
System.out.println("Node data created:" + event.getPath());
}
// 获取跟新后的nodeList
try {
nodeList=zk.getChildren(event.getPath(), false);
} catch (KeeperException e) {
System.out.println(event.getPath()+" has no child, deleted.");
} catch (InterruptedException e) {
e.printStackTrace();
}
// 增加结点
List<String> nodeListNow = nodeList;
if (nodeListBefore.size() < nodeListNow.size()) {
for (String str : nodeListNow) {
if (!nodeListBefore.contains(str)) {
System.out.println("Node created:" + event.getPath() + "/" + str);
}
}
}
// 删除结点
if (nodeListBefore.size() > nodeListNow.size()) {
for (String str : nodeListNow) {
if (!nodeListBefore.contains(str)) {
System.out.println("Node deleted:" + event.getPath() + "/" + str);
}
}
}
}
};
/**
* 监控Path下的节点
*/
while (true) {
try {
zk.exists(path, watcher);// 所要监控的主结点
} catch (Exception e) {
}
try {
nodeList = zk.getChildren(path, watcher);
} catch (Exception e) {
e.printStackTrace();
}
// 对path下每一个结点都设置一个watcher
for (String nodeName : nodeList) {
try {
zk.exists(path + "/" + nodeName, watcher);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
//System.out.println("hhhh");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}