@Autowired //com.ecwid.consul.v1.ConsulClient private ConsulClient consulClient; @PostMapping("/clear/{serviceId}") public void clear(@PathVariable String serviceId) { consulClient.agentServiceDeregister(serviceId); }
- 先通过
consulClient.getHealthServices(serviceId, false, null)
根据serviceId
来获取服务实例清单 - 遍历实例清单中有不是PASSING状态的实例,就调用
client.agentServiceDeregister(serviceId)
来剔除public void clear(@PathVariable String id) { List<HealthService> response = consulClient.getHealthServices(id, false, null).getValue(); for(HealthService service : response) { // 创建一个用来剔除无效实例的ConsulClient,连接到无效实例注册的agent ConsulClient clearClient = new ConsulClient(service.getNode().getAddress(), 8500); service.getChecks().forEach(check -> { if(check.getStatus() != Check.CheckStatus.PASSING) { logger.info("unregister : {}", check.getServiceId()); clearClient.agentServiceDeregister(check.getServiceId()); } }); } }
client
连接的agent
必须是serviceId
注册的agent