使用CuratorWatcher构建Curator客户端

时间:2018-02-12 10:02:38

标签: apache-zookeeper apache-curator

我需要使用Curator客户端来替换zk客户端:

zooKeeper = new ZooKeeper(zkConn, 10000, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
          if (event.getState() == KeeperState.SyncConnected) {
            log("connected.");
            Latch.countDown();
          } else if (event.getState() == KeeperState.Disconnected) {
            log("disconnected.");
          }
        }
      });

我找不到任何带有CuratorWatcher的Curator客户端构造函数。请问如何使用CuratorWatcherto实现上面的代码?

虽然我有一个ieda:

    curator = CuratorFrameworkFactory.newClient(zkConn, retryPolicy);
    curator.start();
    curator.getData().usingWatcher(new CuratorWatcher() {
      @Override
      public void process(WatchedEvent event) throws Exception {
         if (event.getState() == KeeperState.SyncConnected) {
            log("connected.");
            Latch.countDown();
         } else if (event.getState() == KeeperState.Disconnected) {
            log("disconnected.");
         }
  }});

我不知道它是否正确,因为据我所知curator.getData()最后用.forPath(path)构建。我应该使用curator.getState(),因为刚才声明了策展人客户端,肯定没有数据可以获得。

欢迎任何建议,非常感谢您!

1 个答案:

答案 0 :(得分:0)

以这种方式实施:

curator.getConnectionStateListenable().addListener(new ConnectionStateListener() {

      public void stateChanged(CuratorFramework curator, ConnectionState state) {
          if (state == ConnectionState.CONNECTED) {
            log("connected.");
            Latch.countDown();
          } else if (state == ConnectionState.LOST) {
            log("disconnected.");
          }
      }
    });
    curator.start();