千家信息网

spring cloud中ConsulServiceRegistry的用法

发表于:2026-11-01 作者:千家信息网编辑
千家信息网最后更新 2026年11月01日,本篇内容介绍了"spring cloud中ConsulServiceRegistry的用法"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况
千家信息网最后更新 2026年11月01日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 {        /**         * 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  The type of the status.         * @return The status of the registration.         * @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint         */         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 {        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> response = this.client.getHealthChecksForService(serviceId,                                QueryParams.DEFAULT);                List 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 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

"spring cloud中ConsulServiceRegistry的用法"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

方法 任务 服务 内容 参数 同时 接口 更多 知识 构造器 实用 学有所成 接下来 困境 实际 小结 情况 文章 案例 编带 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 美国互联网保险保险科技 互联网科技会 互联网科技的发展 科技互联网创业计划书 上海卓越科技 互联网 深圳卡尔迅互联网科技有限公司怎么样 广西拼得多互联网科技有限公司 哈尔滨新华互联网科技学院 北京大学互联网科技怎么样 温州喔噻互联网科技有限公司 随着互联网科技发展 互联网企业和科技型企业 佳云科技和互联网广告 民营互联网公司国防科技 求路客互联网科技电话 数字互联网科技有限公司 广西泛欧互联网科技有限公司 互联网科技创新方面的资料 互联网科技创业有什么好项目 前海云享互联网科技 互联网科技深圳 互联网科技作文 科技互联网创业计划书 互联网公司会议桌创意科技软装饰 安控科技rtu产品工业互联网 互联网大会黑科技排名 领航科技大厦互联网公司 工业互联网科技创业 广州梦谷互联网科技有限公司领导 北京互联网科技类企业分布
0