@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
參考:http://blog.didispace.com/consul-deregister/