专栏首页码匠的流水账聊聊spring cloud的ConsulServiceRegistry
原创

聊聊spring cloud的ConsulServiceRegistry

本文主要研究一下spring cloud的ConsulServiceRegistry

ServiceRegistry

spring-cloud-commons-2.1.2.RELEASE-sources.jar!/org/springframework/cloud/client/serviceregistry/ServiceRegistry.java

public interface ServiceRegistry<R extends Registration> {
​
    /**
     * Registers the registration. A registration typically has information about an
     * instance, such as its hostname and port.
     * @param registration registration meta data
     */
    void register(R registration);
​
    /**
     * Deregisters the registration.
     * @param registration registration meta data
     */
    void deregister(R registration);
​
    /**
     * Closes the ServiceRegistry. This is a lifecycle method.
     */
    void close();
​
    /**
     * Sets the status of the registration. The status values are determined by the
     * individual implementations.
     * @param registration The registration to update.
     * @param status The status to set.
     * @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint
     */
    void setStatus(R registration, String status);
​
    /**
     * Gets the status of a particular registration.
     * @param registration The registration to query.
     * @param <T> The type of the status.
     * @return The status of the registration.
     * @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint
     */
    <T> T getStatus(R registration);
​
}
  • ServiceRegistry接口定义了register、deregister、close、setStatus、getStatus方法

ConsulServiceRegistry

spring-cloud-consul-discovery-2.1.2.RELEASE-sources.jar!/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistry.java

public class ConsulServiceRegistry implements ServiceRegistry<ConsulRegistration> {
​
    private static Log log = LogFactory.getLog(ConsulServiceRegistry.class);
​
    private final ConsulClient client;
​
    private final ConsulDiscoveryProperties properties;
​
    private final TtlScheduler ttlScheduler;
​
    private final HeartbeatProperties heartbeatProperties;
​
    public ConsulServiceRegistry(ConsulClient client,
            ConsulDiscoveryProperties properties, TtlScheduler ttlScheduler,
            HeartbeatProperties heartbeatProperties) {
        this.client = client;
        this.properties = properties;
        this.ttlScheduler = ttlScheduler;
        this.heartbeatProperties = heartbeatProperties;
    }
​
    @Override
    public void register(ConsulRegistration reg) {
        log.info("Registering service with consul: " + reg.getService());
        try {
            this.client.agentServiceRegister(reg.getService(),
                    this.properties.getAclToken());
            NewService service = reg.getService();
            if (this.heartbeatProperties.isEnabled() && this.ttlScheduler != null
                    && service.getCheck() != null
                    && service.getCheck().getTtl() != null) {
                this.ttlScheduler.add(reg.getInstanceId());
            }
        }
        catch (ConsulException e) {
            if (this.properties.isFailFast()) {
                log.error("Error registering service with consul: " + reg.getService(),
                        e);
                ReflectionUtils.rethrowRuntimeException(e);
            }
            log.warn("Failfast is false. Error registering service with consul: "
                    + reg.getService(), e);
        }
    }
​
    @Override
    public void deregister(ConsulRegistration reg) {
        if (this.ttlScheduler != null) {
            this.ttlScheduler.remove(reg.getInstanceId());
        }
        if (log.isInfoEnabled()) {
            log.info("Deregistering service with consul: " + reg.getInstanceId());
        }
        this.client.agentServiceDeregister(reg.getInstanceId(),
                this.properties.getAclToken());
    }
​
    @Override
    public void close() {
​
    }
​
    @Override
    public void setStatus(ConsulRegistration registration, String status) {
        if (status.equalsIgnoreCase(OUT_OF_SERVICE.getCode())) {
            this.client.agentServiceSetMaintenance(registration.getInstanceId(), true);
        }
        else if (status.equalsIgnoreCase(UP.getCode())) {
            this.client.agentServiceSetMaintenance(registration.getInstanceId(), false);
        }
        else {
            throw new IllegalArgumentException("Unknown status: " + status);
        }
​
    }
​
    @Override
    public Object getStatus(ConsulRegistration registration) {
        String serviceId = registration.getServiceId();
        Response<List<Check>> response = this.client.getHealthChecksForService(serviceId,
                QueryParams.DEFAULT);
        List<Check> checks = response.getValue();
​
        for (Check check : checks) {
            if (check.getServiceId().equals(registration.getInstanceId())) {
                if (check.getName().equalsIgnoreCase("Service Maintenance Mode")) {
                    return OUT_OF_SERVICE.getCode();
                }
            }
        }
​
        return UP.getCode();
    }
​
}
  • ConsulServiceRegistry实现了ServiceRegistry方法,其构造器接收ConsulClient、ConsulDiscoveryProperties、TtlScheduler、HeartbeatProperties参数
  • 其regiter方法使用ConsulClient的agentServiceRegister注册服务,如果开启heartbeat并设置ttl的话,会注册一个heartbeat的延时任务;deregister方法使用ConsulClient的agentServiceDeregister注销服务,同时从ttlScheduler移除该instance的延时任务
  • setStatus方法对OUT_OF_SERVICE执行client.agentServiceSetMaintenance(registration.getInstanceId(), true),对UP执行client.agentServiceSetMaintenance(registration.getInstanceId(), false);getStatus方法通过client.getHealthChecksForService(serviceId,QueryParams.DEFAULT)获取Check列表,一旦有Service Maintenance Mode的check立即返回OUT_OF_SERVICE

ConsulRegistration

spring-cloud-consul-discovery-2.1.2.RELEASE-sources.jar!/org/springframework/cloud/consul/serviceregistry/ConsulRegistration.java

public class ConsulRegistration implements Registration {
​
    private final NewService service;
​
    private ConsulDiscoveryProperties properties;
​
    public ConsulRegistration(NewService service, ConsulDiscoveryProperties properties) {
        this.service = service;
        this.properties = properties;
    }
​
    public NewService getService() {
        return this.service;
    }
​
    protected ConsulDiscoveryProperties getProperties() {
        return this.properties;
    }
​
    public String getInstanceId() {
        return getService().getId();
    }
​
    public String getServiceId() {
        return getService().getName();
    }
​
    @Override
    public String getHost() {
        return getService().getAddress();
    }
​
    @Override
    public int getPort() {
        return getService().getPort();
    }
​
    @Override
    public boolean isSecure() {
        return this.properties.getScheme().equalsIgnoreCase("https");
    }
​
    @Override
    public URI getUri() {
        return DefaultServiceInstance.getUri(this);
    }
​
    @Override
    public Map<String, String> getMetadata() {
        return ConsulServerUtils.getMetadata(getService().getTags());
    }
​
}
  • ConsulRegistration实现了Registration接口,其getMetadata方法返回的是ConsulServerUtils.getMetadata(getService().getTags())

ConsulServiceRegistryAutoConfiguration

spring-cloud-consul-discovery-2.1.2.RELEASE-sources.jar!/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryAutoConfiguration.java

@Configuration
@ConditionalOnConsulEnabled
@ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", matchIfMissing = true)
@AutoConfigureBefore(ServiceRegistryAutoConfiguration.class)
public class ConsulServiceRegistryAutoConfiguration {
​
    @Autowired(required = false)
    private TtlScheduler ttlScheduler;
​
    @Bean
    @ConditionalOnMissingBean
    public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient,
            ConsulDiscoveryProperties properties,
            HeartbeatProperties heartbeatProperties) {
        return new ConsulServiceRegistry(consulClient, properties, this.ttlScheduler,
                heartbeatProperties);
    }
​
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnProperty("spring.cloud.consul.discovery.heartbeat.enabled")
    public TtlScheduler ttlScheduler(ConsulClient consulClient,
            HeartbeatProperties heartbeatProperties) {
        return new TtlScheduler(heartbeatProperties, consulClient);
    }
​
    @Bean
    @ConditionalOnMissingBean
    public HeartbeatProperties heartbeatProperties() {
        return new HeartbeatProperties();
    }
​
    @Bean
    @ConditionalOnMissingBean
    public ConsulDiscoveryProperties consulDiscoveryProperties(InetUtils inetUtils) {
        return new ConsulDiscoveryProperties(inetUtils);
    }
​
}
  • ConsulServiceRegistryAutoConfiguration注册了ConsulServiceRegistry、TtlScheduler、HeartbeatProperties、ConsulDiscoveryProperties

小结

  • ConsulServiceRegistry实现了ServiceRegistry方法,其构造器接收ConsulClient、ConsulDiscoveryProperties、TtlScheduler、HeartbeatProperties参数
  • 其regiter方法使用ConsulClient的agentServiceRegister注册服务,如果开启heartbeat并设置ttl的话,会注册一个heartbeat的延时任务;deregister方法使用ConsulClient的agentServiceDeregister注销服务,同时从ttlScheduler移除该instance的延时任务
  • setStatus方法对OUT_OF_SERVICE执行client.agentServiceSetMaintenance(registration.getInstanceId(), true),对UP执行client.agentServiceSetMaintenance(registration.getInstanceId(), false);getStatus方法通过client.getHealthChecksForService(serviceId,QueryParams.DEFAULT)获取Check列表,一旦有Service Maintenance Mode的check立即返回OUT_OF_SERVICE

doc

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Android设计模式应用-代理模式

    其实每个模式名称就表明了该模式的作用,代理模式就是多一个代理类出来,替原对象进行一些操作,比如我们在租房子的时候回去找中介,为什么呢?因为 你对该地区房屋的信息...

    wust小吴
  • Android设计模式应用-装饰器模式

    给一个对象动态的添加方法,就是装饰器模式,通常的做法就是将   原始对象作为一个参数传递给  装饰者构造器

    wust小吴
  • java 图片相似度判判断

    这阵子发现我的图像数据库中有不少内容一样的图像需要剔除,这些内容一样的图像可能尺寸不一样,通道数也可能不一样(灰度/彩色),如下三张图内容完全一样,只是亮度或色...

    DencyCheng
  • 实习入职第九天:MediaPlayer添加进度条的两种方式

    然后在onPrepare()里面post出去,在程序退出的时候销毁handler.removeCallback(runnable)

    wust小吴
  • Kotlin 开发者社区: Kotlin collections (集合类)

    Nicolas Fränkel is a Developer Advocate with 15+ years experience consulting for...

    一个会写诗的程序员
  • Android设计模式应用-桥接模式

    桥接模式就是把事物和其具体实现分开,使他们可以各自独立的变化。桥接的用意是:将抽象化与实现化解耦,使得二者可以独立变化

    wust小吴
  • java学习---new的对象怎么被内存回收

    如上面代码,简单说就是new User()的时候,会返回一个地址,并且将地址赋值给引用u,当这个引用被u持有的时候,java会认为这个对象时有用的,不会回收对...

    wust小吴
  • 实习杂记(27):如何解决Java.lang.NoClassDefFoundError

    其中第7点就是我碰到的原因,在android中主dex调用子dex的类,那肯定是不行的,因为那个时候子dex还没有加载,那么调用的类肯定就不行了,

    wust小吴
  • Android基础部分再学习---activity的状态保存

    参考地址:http://blog.csdn.net/lonelyroamer/article/details/18715975

    wust小吴
  • 实习杂记(21):LocalBroadcastManager的使用、优点在哪里?

           它来自Android 的support包,类名是android.support.v4.content.LocalBroadcastManager...

    wust小吴

扫码关注云+社区

领取腾讯云代金券