SpringCloud Consul自定义服务注册

SpringCloud自定义consul服务注册器,获取特定的本地地址进行注册,注销的时候检查并注销其他无效实例

package com.mk.springcloud.config;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ecwid.consul.v1.health.HealthServicesRequest;
import com.ecwid.consul.v1.health.model.Check;
import com.ecwid.consul.v1.health.model.HealthService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry;
import org.springframework.stereotype.Service;

import java.net.Inet4Address;
import java.util.*;

@Service
public class ConsulRegistry extends ConsulServiceRegistry {

    private ConsulDiscoveryProperties properties;

    private ConsulClient consulClient;

    @Value("${spring.application.name}")
    private String applicationName;

    public ConsulRegistry(ConsulClient client, ConsulDiscoveryProperties properties, @Autowired(required = false) TtlScheduler ttlScheduler, HeartbeatProperties heartbeatProperties) {
        super(client, properties, ttlScheduler, heartbeatProperties);
        this.properties = properties;
        this.consulClient = client;
    }

    @SneakyThrows
    @Override
    public void register(ConsulRegistration reg) {
        //获取服务器的ip
        String address = Inet4Address.getLocalHost().getHostAddress();
        NewService newService = reg.getService();
        newService.setAddress(address);
        newService.getCheck().setHttp("http://" + address + ":" + reg.getService().getPort() + properties.getHealthCheckPath());
        newService.setId(reg.getService().getName() + "-" + address + ":" + reg.getService().getPort() + "-" + UUID.randomUUID().toString().replace("-",""));
        super.register(reg);
    }

    @Override
    public void deregister(ConsulRegistration reg) {
        super.deregister(reg);

        //查询no pass的服务实例
        HealthServicesRequest request = HealthServicesRequest.newBuilder().setPassing(false).build();
        List<HealthService> services = consulClient.getHealthServices(applicationName, request).getValue();

        for (HealthService service : services) {
            for (Check check : service.getChecks()) {
                //注销无效实例
                if (check.getStatus() != Check.CheckStatus.PASSING) {
                    consulClient.agentServiceDeregister(check.getServiceId());
                }
            }
        }
    }
}

 

posted @ 2021-05-22 21:53  茅坤宝骏氹  阅读(5)  评论(0)    收藏  举报  来源