千家信息网

spring cloud consul中TtlScheduler的原理和作用是什么

发表于:2026-11-03 作者:千家信息网编辑
千家信息网最后更新 2026年11月03日,这篇文章主要讲解了"spring cloud consul中TtlScheduler的原理和作用是什么",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"s
千家信息网最后更新 2026年11月03日spring cloud consul中TtlScheduler的原理和作用是什么

这篇文章主要讲解了"spring cloud consul中TtlScheduler的原理和作用是什么",文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习"spring cloud consul中TtlScheduler的原理和作用是什么"吧!

序

本文主要研究一下spring cloud consul的TtlScheduler

TtlScheduler

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

public class TtlScheduler {        private static final Log log = LogFactory.getLog(ConsulDiscoveryClient.class);        private final Map serviceHeartbeats = new ConcurrentHashMap<>();        private final TaskScheduler scheduler = new ConcurrentTaskScheduler(                        Executors.newSingleThreadScheduledExecutor());        private HeartbeatProperties configuration;        private ConsulClient client;        public TtlScheduler(HeartbeatProperties configuration, ConsulClient client) {                this.configuration = configuration;                this.client = client;        }        @Deprecated        public void add(final NewService service) {                add(service.getId());        }        /**         * Add a service to the checks loop.         * @param instanceId instance id         */        public void add(String instanceId) {                ScheduledFuture task = this.scheduler.scheduleAtFixedRate(                                new ConsulHeartbeatTask(instanceId), this.configuration                                                .computeHearbeatInterval().toStandardDuration().getMillis());                ScheduledFuture previousTask = this.serviceHeartbeats.put(instanceId, task);                if (previousTask != null) {                        previousTask.cancel(true);                }        }        public void remove(String instanceId) {                ScheduledFuture task = this.serviceHeartbeats.get(instanceId);                if (task != null) {                        task.cancel(true);                }                this.serviceHeartbeats.remove(instanceId);        }        private class ConsulHeartbeatTask implements Runnable {                private String checkId;                ConsulHeartbeatTask(String serviceId) {                        this.checkId = serviceId;                        if (!this.checkId.startsWith("service:")) {                                this.checkId = "service:" + this.checkId;                        }                }                @Override                public void run() {                        TtlScheduler.this.client.agentCheckPass(this.checkId);                        if (log.isDebugEnabled()) {                                log.debug("Sending consul heartbeat for: " + this.checkId);                        }                }        }}
  • TtlScheduler的构造器接收HeartbeatProperties、ConsulClient;add方法会往scheduler注册一个定时执行的ConsulHeartbeatTask,执行间隔由HeartbeatProperties的ttlValue及intervalRatio计算而来,同时如果previousTask不为null则对其进行cancel;remove方法则cancel调用ScheduledFuture,然后将其从serviceHeartbeats中移除;ConsulHeartbeatTask的run方法则是执行client.agentCheckPass

HeartbeatProperties

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

@ConfigurationProperties(prefix = "spring.cloud.consul.discovery.heartbeat")@Validatedpublic class HeartbeatProperties {        private static final Log log = org.apache.commons.logging.LogFactory                        .getLog(HeartbeatProperties.class);        // TODO: change enabled to default to true when I stop seeing messages like        // [WARN] agent: Check 'service:testConsulApp:xtest:8080' missed TTL, is now critical        boolean enabled = false;        @Min(1)        private int ttlValue = 30;        @NotNull        private String ttlUnit = "s";        @DecimalMin("0.1")        @DecimalMax("0.9")        private double intervalRatio = 2.0 / 3.0;        // TODO: did heartbeatInterval need to be a field?        protected Period computeHearbeatInterval() {                // heartbeat rate at ratio * ttl, but no later than ttl -1s and, (under lesser                // priority), no sooner than 1s from now                double interval = this.ttlValue * this.intervalRatio;                double max = Math.max(interval, 1);                int ttlMinus1 = this.ttlValue - 1;                double min = Math.min(ttlMinus1, max);                Period heartbeatInterval = new Period(Math.round(1000 * min));                log.debug("Computed heartbeatInterval: " + heartbeatInterval);                return heartbeatInterval;        }        public String getTtl() {                return this.ttlValue + this.ttlUnit;        }        public boolean isEnabled() {                return this.enabled;        }        public void setEnabled(boolean enabled) {                this.enabled = enabled;        }        public @Min(1) int getTtlValue() {                return this.ttlValue;        }        public void setTtlValue(@Min(1) int ttlValue) {                this.ttlValue = ttlValue;        }        public @NotNull String getTtlUnit() {                return this.ttlUnit;        }        public void setTtlUnit(@NotNull String ttlUnit) {                this.ttlUnit = ttlUnit;        }        public @DecimalMin("0.1") @DecimalMax("0.9") double getIntervalRatio() {                return this.intervalRatio;        }        public void setIntervalRatio(                        @DecimalMin("0.1") @DecimalMax("0.9") double intervalRatio) {                this.intervalRatio = intervalRatio;        }        @Override        public String toString() {                return new ToStringCreator(this).append("enabled", this.enabled)                                .append("ttlValue", this.ttlValue).append("ttlUnit", this.ttlUnit)                                .append("intervalRatio", this.intervalRatio).toString();        }}
  • HeartbeatProperties有ttlValue、intervalRatio等属性,其computeHearbeatInterval方法会取ttlMinus1及Math.max(interval, 1)的最小值作为heartbeatInterval

ConsulDiscoveryClientConfiguration

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

@Configuration@ConditionalOnConsulEnabled@ConditionalOnProperty(value = "spring.cloud.consul.discovery.enabled", matchIfMissing = true)@ConditionalOnDiscoveryEnabled@EnableConfigurationProperties@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class,                CommonsClientAutoConfiguration.class })public class ConsulDiscoveryClientConfiguration {        /**         * Name of the catalog watch task scheduler bean.         */        public static final String CATALOG_WATCH_TASK_SCHEDULER_NAME = "catalogWatchTaskScheduler";        @Autowired        private ConsulClient consulClient;        @Bean        @ConditionalOnMissingBean        @ConditionalOnProperty("spring.cloud.consul.discovery.heartbeat.enabled")        // TODO: move to service-registry for Edgware        public TtlScheduler ttlScheduler(HeartbeatProperties heartbeatProperties) {                return new TtlScheduler(heartbeatProperties, this.consulClient);        }        @Bean        @ConditionalOnMissingBean        // TODO: move to service-registry for Edgware        public HeartbeatProperties heartbeatProperties() {                return new HeartbeatProperties();        }        @Bean        @ConditionalOnMissingBean        // TODO: Split appropriate values to service-registry for Edgware        public ConsulDiscoveryProperties consulDiscoveryProperties(InetUtils inetUtils) {                return new ConsulDiscoveryProperties(inetUtils);        }        @Bean        @ConditionalOnMissingBean        public ConsulDiscoveryClient consulDiscoveryClient(                        ConsulDiscoveryProperties discoveryProperties) {                return new ConsulDiscoveryClient(this.consulClient, discoveryProperties);        }        @Bean        @ConditionalOnMissingBean        @ConditionalOnProperty(name = "spring.cloud.consul.discovery.catalog-services-watch.enabled", matchIfMissing = true)        public ConsulCatalogWatch consulCatalogWatch(                        ConsulDiscoveryProperties discoveryProperties,                        @Qualifier(CATALOG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) {                return new ConsulCatalogWatch(discoveryProperties, this.consulClient,                                taskScheduler);        }        @Bean(name = CATALOG_WATCH_TASK_SCHEDULER_NAME)        @ConditionalOnProperty(name = "spring.cloud.consul.discovery.catalog-services-watch.enabled", matchIfMissing = true)        public TaskScheduler catalogWatchTaskScheduler() {                return new ThreadPoolTaskScheduler();        }}
  • ConsulDiscoveryClientConfiguration在@ConditionalOnMissingBean以及@ConditionalOnProperty("spring.cloud.consul.discovery.heartbeat.enabled")的条件下会自动注册ttlScheduler

小结

TtlScheduler的构造器接收HeartbeatProperties、ConsulClient;add方法会往scheduler注册一个定时执行的ConsulHeartbeatTask,执行间隔由HeartbeatProperties的ttlValue及intervalRatio计算而来,同时如果previousTask不为null则对其进行cancel;remove方法则cancel调用ScheduledFuture,然后将其从serviceHeartbeats中移除;ConsulHeartbeatTask的run方法则是执行client.agentCheckPass

感谢各位的阅读,以上就是"spring cloud consul中TtlScheduler的原理和作用是什么"的内容了,经过本文的学习后,相信大家对spring cloud consul中TtlScheduler的原理和作用是什么这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!

方法 作用 原理 学习 内容 同时 构造器 研究 最小 小结 就是 属性 思路 情况 文章 更多 条件 知识 知识点 篇文章 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 哈尔滨大商圈互联网科技有限公司 朗新科技与工业互联网 科技互联网技术 中资互联网科技 互联网金融 科技 上海互联网科技有限公司 广州互联网络科技有限公司 北京禾田雨橡互联网科技 联恩商钥互联网科技有限公司 深圳互联网科技怎么样 安控科技rtu产品工业互联网 华服互联网科技官网 米聚互联网科技南京有限公司排面 互联网科技创新的路径 互联网科技圈年度人物 四川互联网展示科技馆设计 互联网领先科技宣传片 艺电能源互联网科技有限公司招聘 云南互联网科技学费 六子台科技互联网展会 互联网科技工作委员会副主任毛军 互联网科技小额贷款 镁科技互联网资讯平台 安控科技rtu产品工业互联网 互联网实体化科技化 互联网公司高科技产品 云鲸互联网络科技有限公司 互联网科技职业技能培训学校 科技信息时代互联网发展 互联网科技自媒体灵感
0