3

我正在使用 Apache Curator 进行服务发现,并PathChildrenCache在添加/更新/删除服务时监听事件。

PathChildrenCache pathCache = new PathChildrenCache(client, "/directory", true);
pathCache.getListenable().addListener(new PathChildrenCacheListener() {
  @Override
  public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
    if(event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED) {
      System.out.println("Added");
    }else if(event.getType() == PathChildrenCacheEvent.Type.CHILD_UPDATED) {
      System.out.println("Updated");
    }else if(event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) {
      System.out.println("Removed");
    }
  }
}
pathCache.start();

当我通过 注册服务时org.apache.curator.x.discovery.ServiceDiscovery,我得到了一个附加事件。但是当我取消注册服务时,我没有收到删除的事件。

我如何正确收听服务事件?

4

1 回答 1

1

我最终使用ServiceCacheListener如下(问题是您需要ServiceCache为要观看的每个服务提供一个实例):

ServiceCache<String> serviceCache = serviceDiscovery.serviceCacheBuilder().name("my-service").build();
serviceCache.addListener(new ServiceCacheListener() {

  @Override
  public void stateChanged(CuratorFramework client, ConnectionState newState)
  {
    log.debug("State changed");
  }

  @Override
  public void cacheChanged()
  {
    log.debug("Cache changed");
  }
}, Executors.newSingleThreadExecutor());
serviceCache.start();
于 2015-04-22T10:47:45.397 回答