专栏首页码匠的流水账聊聊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

  • spring-cloud-consul-discovery

本文分享自微信公众号 - 码匠的流水账(geek_luandun),作者:码匠乱炖

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2019-07-22

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 聊聊spring cloud的ConsulServiceRegistry

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

    codecraft
  • 聊聊spring cloud的AbstractLoadBalancingClient

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

    codecraft
  • 聊聊spring cloud的RequestRateLimiterGatewayFilter

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

    codecraft
  • 聊聊spring cloud的ConsulServiceRegistry

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

    codecraft
  • springboot+security整合3

      这篇讲解如何自定义鉴权过程,实现根据数据库查询出的url和method是否匹配当前请求的url和method来决定有没有权限。security鉴权过程如下:...

    用户2038589
  • springboot+security整合(3)自定义鉴权

      这篇讲解如何自定义鉴权过程,实现根据数据库查询出的 url 和 method 是否匹配当前请求的 url 和 method 来决定有没有权限。securit...

    用户2038589
  • 聊聊ExecutorService的监控

    metrics-core-4.0.2-sources.jar!/com/codahale/metrics/InstrumentedExecutorService...

    codecraft
  • WPF 最小的代码使用 DynamicRenderer 书写 输入层设置宽高视觉树

    在 WPF 中有 DynamicRenderer 提供高性能的书写,这个类在 WPF 只有 InkCanvas 使用,如果想要在自己的 UIElement 使用...

    林德熙
  • webclient对reactor-netty的封装

    本文主要研究一下spring 5的WebClient对reactor-netty的HttpClient的封装

    codecraft
  • 对JiaThis Flash XSS的挖掘与分析

    到360官微在微博上说了, http://www.jiathis.com/code/swf/m.swf 存在XSS漏洞,可以导致使用了JiaThis的任意网站产...

    phith0n

扫码关注云+社区

领取腾讯云代金券