首页 > 解决方案 > 监控 znode 子节点上的 Zookeeper 添加和删除

问题描述

我正在寻找一个 Zookeeper 配方来监控在父节点中执行的操作(添加子节点、删除子节点等)

我无法弄清楚如何使用观察者来获取事件。任何帮助表示赞赏。

import org.apache.zookeeper.*;
import java.io.IOException;

public class ZookeeperMonitor {
    private static ZooKeeper zookeeper;

    public ZooKeeper connect(String connectionString, int port) throws IOException, InterruptedException {
        ZookeeperWatcher watcher = new ZookeeperWatcher();
        zookeeper = new ZooKeeper(connectionString, port, watcher);

        return zookeeper;
    }

    public void checkForChanges() throws KeeperException, InterruptedException {
        zookeeper.getChildren("/parent",new ChildChangeWatcher());
    }
}


class ZookeeperWatcher implements Watcher {

    public void process(WatchedEvent watchedEvent) {
    }
}

class ChildChangeWatcher implements  Watcher {
    public void process(WatchedEvent e) {
        if(e.getType() == Event.EventType.NodeChildrenChanged){
            System.out.println("change in children");
        }
    }
}

如何将其作为长时间运行的守护程序运行?

watcher足够单独或者我应该使用callback. 我不明白这里回调的目的。

标签: apache-zookeeper

解决方案


你不需要孩子的观察者,让 parentNode 实现观察者

public void checkForChanges() throws KeeperException, InterruptedException { zookeeper.getChildren("/parent",this); }


推荐阅读