文档章节

聊聊spring cloud的ConsulServiceRegistry

go4it
 go4it
发布于 07/22 23:43
字数 840
阅读 28
收藏 1

本文主要研究一下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

© 著作权归作者所有

go4it
粉丝 87
博文 1066
码字总数 1011844
作品 0
深圳
私信 提问
Spring Cloud Finchley.SR1 的学习与应用 4 - 服务注册

Spring Cloud Consul 简介 Spring Cloud Consul项目是针对Consul的服务治理实现。Consul是一个分布式高可用的系统,它包含多个组件,但是作为一个整体,在微服务架构中为我们的基础设施提供服...

张shieppp
2018/11/21
42
0
Spring Cloud Alibaba与Spring Boot、Spring Cloud之间不得不说的版本关系

这篇博文是临时增加出来的内容,主要是由于最近连载《Spring Cloud Alibaba基础教程》系列的时候,碰到读者咨询的大量问题中存在一个比较普遍的问题:版本的选择。其实这类问题,在之前写Spr...

程序猿DD
03/03
394
0
聊聊spring cloud gateway的GatewayFilter

序 本文主要研究一下spring cloud gateway的GatewayFilter GatewayFilter spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gateway/filter/GatewayFilter.jav......

go4it
2018/06/09
747
0
Spring Cloud 入门教程:聊聊Spring Cloud

一、 Spring Cloud 是什么? Spring Cloud 是将分布式系统中一系列基础框架/工具进行整合的框架。其中包含:服务注册与发现、服务网关、熔断器、配置中心、消息中心、服务链路追踪等等。 Sp...

吴伟祥
2018/12/03
456
0
聊聊spring.cloud.gateway.default-filters

序 本文主要研究下spring.cloud.gateway.default-filters 配置 default-filters,配置的是FilterDefinition对象 FilterDefinition spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/sp......

go4it
2018/06/01
494
0

没有更多内容

加载失败,请刷新页面

加载更多

maven 环境隔离

解决问题 即 在 resource 文件夹下面 ,新增对应的资源配置文件夹,对应 开发,测试,生产的不同的配置内容 <resources> <resource> <directory>src/main/resources.${deplo......

之渊
今天
8
0
Linux创建yum仓库

第一步、搞定自己的光盘 #创建文件夹 mkdir -p /media/cdrom #挂载光盘 mount /dev/cdrom /media/cdrom #编辑配置文件使其永久生效 vim /etc/fstab 第二步,编辑yun源 vim /ect yum.repos.d...

究极小怪兽zzz
今天
6
0
jar 更新部分文件

C:\Program Files (x86)\Java\jdk1.8.0_102\bin>jar -hIllegal option: hUsage: jar {ctxui}[vfmn0PMe] [jar-file] [manifest-file] [entry-point] [-C dir] files ...Options: -c c......

圣洁之子
今天
9
0
OSChina 周六乱弹 —— 感谢女装红薯开办了这个网站

Osc乱弹歌单(2019)请戳(这里) 【今日歌曲】 @胖达panda:分享歌词: 我有一只小毛驴我从来也不骑,有一天我心血来潮骑着去赶集,我手里拿着小皮鞭我心里正得意,不知怎么哗啦啦,我摔了一...

小小编辑
今天
2.6K
13
DDD(四)

1,引言 软件开发者大多趋向于将关注点放在数据上,而不是领域上。这对于刚入门的DDD的新手而言也是如此。以我目前的思考方式,数据库依然占据主要的地位。开发一个功能,首先我就会考虑我会...

MrYuZixian
昨天
7
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部