首页 > 解决方案 > Zookeeper 馆长观察者未收到任何事件

问题描述

我一直在尝试将 apache curator 用于 zookeeper,但无法取得进展。我正在寻找的只是在 zk 节点上设置一个观察者并监听该特定节点上的所有数据更改。我写了一个简单的程序来试试这个,但我没有收到任何事件。这是我的代码:

CuratorFramework curator = new ZookeeperClient(zkHosts).getConnection();

    CompletableFuture.runAsync(() -> {
        CuratorWatcher curatorWatcher = event -> System.out.println("Watched event: " + event);

        try {
            curator.getChildren().usingWatcher(curatorWatcher).forPath(NODE_PATH);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

    CompletableFuture.runAsync(() -> {
        try {
            curator.setData().forPath(NODE_PATH, "randomdata1".getBytes());
            curator.setData().forPath(NODE_PATH, "randomdata2".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

谢谢您的帮助!

标签: apache-zookeeperapache-curator

解决方案


在 Zookeeper 中,getData() 和 exists() 设置数据监视。getChildren() 设置子手表;有关更多详细信息,请参阅ZooKeeper 监视

您应该在第一个中使用curator.getData()而不是curator.getChildren()在第一个中使用,runAsync()因为您setData()在第二个中使用runAsync()

如果你想保留curator.getChildren(),那么你应该在NODE_PATH测试下添加一个新的孩子


推荐阅读