我正在使用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
注册服务时,出现了一个附加事件。但是,当我取消注册服务时,没有得到删除的事件。如何正确收听服务事件?
最佳答案
我最终使用了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();