十、springcloud之Consul注销实例

@Autowired  //com.ecwid.consul.v1.ConsulClient
    private ConsulClient consulClient;

/**
     * @param serviceId
     */
    @ApiOperation(value="剔除服务实例", notes="剔除服务实例") 
    @ApiImplicitParam(name = "serviceId", value = "服务ID", required = true, paramType="path")
    @PostMapping("/clear/{serviceId}")
    public void clear(@PathVariable String serviceId) {
        log.info("下线服务-" + serviceId);
        consulClient.agentServiceDeregister(serviceId);
    }
  • 先通过consulClient.getHealthServices(serviceId, false, null)根据serviceId来获取服务实例清单
  • 遍历实例清单中有不是PASSING状态的实例,就调用client.agentServiceDeregister(serviceId)来剔除
    /**
         * @param serviceId
         */
        @ApiOperation(value="剔除服务实例", notes="剔除服务实例") 
        @ApiImplicitParam(name = "serviceId", value = "服务ID", required = true, paramType="path")
        @PostMapping("/clear/{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/

猜你喜欢

转载自www.cnblogs.com/soul-wonder/p/9254203.html