【Eureka】【源码+图解】【六】Eureka的续约功能

2024-01-05 18:40

本文主要是介绍【Eureka】【源码+图解】【六】Eureka的续约功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【Eureka】【源码+图解】【五】Eureka的注册功能

目录

  • 5. 续约
    • 5.1 初始化
    • 5.2 TimedSupervisorTask
    • 5.3 renew()
    • 5.4 服务端收到renew请求
    • 5.5 服务端更新实例续约信息
    • 5.6 同步到其他server节点

5. 续约

先看下整体流程

在这里插入图片描述
接下来分析绿色的6个步骤

5.1 初始化

public class DiscoveryClient implements EurekaClient {private final ThreadPoolExecutor heartbeatExecutor;private TimedSupervisorTask heartbeatTask;DiscoveryClient(...) {// 1. 创建续约线程池heartbeatExecutor = new ThreadPoolExecutor(1, // eureka.client.heartbeatExecutorThreadPoolSize,默认2clientConfig.getHeartbeatExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(),new ThreadFactoryBuilder().setNameFormat("DiscoveryClient-HeartbeatExecutor-%d").setDaemon(true).build());}private void initScheduledTasks() {if (clientConfig.shouldRegisterWithEureka()) {// eureka.instance.leaseRenewalIntervalInSeconds,续约间隔,默认30int renewalIntervalInSecs = instanceInfo.getLeaseInfo().getRenewalIntervalInSecs();// eureka.client.heartbeatExecutorExponentialBackOffBound,默认10int expBackOffBound = clientConfig.getHeartbeatExecutorExponentialBackOffBound();// 2. 包装成定时任务heartbeatTask = new TimedSupervisorTask("heartbeat",scheduler,heartbeatExecutor,renewalIntervalInSecs,TimeUnit.SECONDS,expBackOffBound,new HeartbeatThread() // 续约的真正逻辑);// 3. 开启定时任务scheduler.schedule(heartbeatTask,renewalIntervalInSecs, TimeUnit.SECONDS);}}
}

5.2 TimedSupervisorTask

public class TimedSupervisorTask extends TimerTask {@Overridepublic void run() {Future<?> future = null;try {// 提交续约task到线程池future = executor.submit(task);// 阻塞等待直到返回结果或者超时future.get(timeoutMillis, TimeUnit.MILLISECONDS);// 下一次延时任务的时间delay.set(timeoutMillis);} catch (TimeoutException e) {// 等待结果超时,指数级增长超时时间// 第一次:currentDelay// 第二次:currentDelay * 2// ...// 第n+1次:currentDelay * 2^n// currentDelay * 2^n 必须小于eureka.instance.leaseRenewalIntervalInSeconds * eureka.client.heartbeatExecutorExponentialBackOffBound// 否则取两者间最小值timeoutCounter.increment();long currentDelay = delay.get();long newDelay = Math.min(maxDelay, currentDelay * 2);delay.compareAndSet(currentDelay, newDelay);} catch (RejectedExecutionException e) {rejectedCounter.increment();} catch (Throwable e) {throwableCounter.increment();} finally {if (future != null) {future.cancel(true);}if (!scheduler.isShutdown()) {// 定时下一次续约时间scheduler.schedule(this, delay.get(), TimeUnit.MILLISECONDS);}}}
}

5.3 renew()

HeartbeatThread获得线程资源,执行run()方法

public class DiscoveryClient implements EurekaClient {private class HeartbeatThread implements Runnable {public void run() {// 执行续约请求if (renew()) {lastSuccessfulHeartbeatTimestamp = System.currentTimeMillis();}}}boolean renew() {EurekaHttpResponse<InstanceInfo> httpResponse;try {// 发送续约请求httpResponse = eurekaTransport.registrationClient.sendHeartBeat(instanceInfo.getAppName(), instanceInfo.getId(), instanceInfo, null);if (httpResponse.getStatusCode() == Status.NOT_FOUND.getStatusCode()) {// 续约失败,重新注册boolean success = register();......return success;}return httpResponse.getStatusCode() == Status.OK.getStatusCode();} catch (Throwable e) {logger.error(PREFIX + "{} - was unable to send heartbeat!", appPathIdentifier, e);return false;}}
}

5.4 服务端收到renew请求

public class InstanceResource {@PUTpublic Response renewLease(@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication,@QueryParam("overriddenstatus") String overriddenStatus,@QueryParam("status") String status,@QueryParam("lastDirtyTimestamp") String lastDirtyTimestamp) {// 客户端发过来的请求为false,需要同步到其他server节点boolean isFromReplicaNode = "true".equals(isReplication);boolean isSuccess = registry.renew(app.getName(), id, isFromReplicaNode);......return response;}
}

5.5 服务端更新实例续约信息

public abstract class AbstractInstanceRegistry implements InstanceRegistry {public boolean renew(String appName, String id, boolean isReplication) {// 1. 获取实例所属的应用Map<String, Lease<InstanceInfo>> gMap = registry.get(appName);Lease<InstanceInfo> leaseToRenew = null;// 2. 获取旧的实例信息if (gMap != null) {leaseToRenew = gMap.get(id);}if (leaseToRenew == null) {return false;} else {InstanceInfo instanceInfo = leaseToRenew.getHolder();if (instanceInfo != null) {// 3. 更新statusInstanceStatus overriddenInstanceStatus = this.getOverriddenInstanceStatus(instanceInfo, leaseToRenew, isReplication);if (overriddenInstanceStatus == InstanceStatus.UNKNOWN) {return false;}if (!instanceInfo.getStatus().equals(overriddenInstanceStatus)) {instanceInfo.setStatusWithoutDirty(overriddenInstanceStatus);}}renewsLastMin.increment();// 4. 更新lastUpdateTimestamp以便服务端服务剔除时检查检查leaseToRenew.renew();return true;}}// 获取实例的更新状态protected InstanceInfo.InstanceStatus getOverriddenInstanceStatus(InstanceInfo r,Lease<InstanceInfo> existingLease,boolean isReplication) {// InstanceStatus: UP, DOWN, STARTING, OUT_OF_SERVICE, UNKNOWN;InstanceStatusOverrideRule rule = new FirstMatchWinsCompositeRule(// 如果r是UP or OUT_OF_SERVICE,继续往下判断;否则返回相应的值new DownOrStartingRule(),  // 如果r不在overriddenInstanceStatusMap中继续往下判断,否则返回相应值new OverrideExistsRule(overriddenInstanceStatusMap), // 如果existingLease不为空且其值都不是UP or OUT_OF_SERVICE继续往下判断,否则返回相应的值new LeaseExistsRule(), // 返回r的statusnew AlwaysMatchInstanceStatusRule());return rule.apply(r, existingLease, isReplication).status();}
}

5.6 同步到其他server节点

public class PeerAwareInstanceRegistryImpl extends AbstractInstanceRegistry implements PeerAwareInstanceRegistry {public boolean renew(final String appName, final String id, final boolean isReplication) {if (super.renew(appName, id, isReplication)) {// 复制到其他server节点,后面的除了Action.Heartbeat,其他的与register相同,参考4.7节replicateToPeers(Action.Heartbeat, appName, id, null, null, isReplication);return true;}return false;}
}

Eureka的续约功能整体流程就讲完了。

未完待续

这篇关于【Eureka】【源码+图解】【六】Eureka的续约功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/573791

相关文章

Qt实现对Word网页的读取功能

《Qt实现对Word网页的读取功能》文章介绍了几种在Qt中实现Word文档(.docx/.doc)读写功能的方法,包括基于QAxObject的COM接口调用、DOCX模板替换及跨平台解决方案,重点讨论... 目录1. 核心实现方式2. 基于QAxObject的COM接口调用(Windows专用)2.1 环境

SpringBoot+Vue3整合SSE实现实时消息推送功能

《SpringBoot+Vue3整合SSE实现实时消息推送功能》在日常开发中,我们经常需要实现实时消息推送的功能,这篇文章将基于SpringBoot和Vue3来简单实现一个入门级的例子,下面小编就和大... 目录前言先大概介绍下SSE后端实现(SpringBoot)前端实现(vue3)1. 数据类型定义2.

SpringBoot整合Apache Spark实现一个简单的数据分析功能

《SpringBoot整合ApacheSpark实现一个简单的数据分析功能》ApacheSpark是一个开源的大数据处理框架,它提供了丰富的功能和API,用于分布式数据处理、数据分析和机器学习等任务... 目录第一步、添加android依赖第二步、编写配置类第三步、编写控制类启动项目并测试总结ApacheS

Python实现繁体转简体功能的三种方案

《Python实现繁体转简体功能的三种方案》在中文信息处理中,繁体字与简体字的转换是一个常见需求,无论是处理港澳台地区的文本数据,还是开发面向不同中文用户群体的应用,繁简转换都是不可或缺的功能,本文将... 目录前言为什么需要繁简转换?python实现方案方案一:使用opencc库方案二:使用zhconv库

Qt实现删除布局与布局切换功能

《Qt实现删除布局与布局切换功能》在Qt应用开发中,动态管理布局是一个常见需求,比如根据用户操作动态删除某个布局,或在不同布局间进行切换,本文将详细介绍如何实现这些功能,并通过完整示例展示具体操作,需... 目录一、Qt动态删除布局1. 布局删除的注意事项2. 动态删除布局的实现步骤示例:删除vboxLay

Spring Boot整合Redis注解实现增删改查功能(Redis注解使用)

《SpringBoot整合Redis注解实现增删改查功能(Redis注解使用)》文章介绍了如何使用SpringBoot整合Redis注解实现增删改查功能,包括配置、实体类、Repository、Se... 目录配置Redis连接定义实体类创建Repository接口增删改查操作示例插入数据查询数据删除数据更

使用EasyPoi快速导出Word文档功能的实现步骤

《使用EasyPoi快速导出Word文档功能的实现步骤》EasyPoi是一个基于ApachePOI的开源Java工具库,旨在简化Excel和Word文档的操作,本文将详细介绍如何使用EasyPoi快速... 目录一、准备工作1、引入依赖二、准备好一个word模版文件三、编写导出方法的工具类四、在Export

JS纯前端实现浏览器语音播报、朗读功能的完整代码

《JS纯前端实现浏览器语音播报、朗读功能的完整代码》在现代互联网的发展中,语音技术正逐渐成为改变用户体验的重要一环,下面:本文主要介绍JS纯前端实现浏览器语音播报、朗读功能的相关资料,文中通过代码... 目录一、朗读单条文本:① 语音自选参数,按钮控制语音:② 效果图:二、朗读多条文本:① 语音有默认值:②

C#实现高性能拍照与水印添加功能完整方案

《C#实现高性能拍照与水印添加功能完整方案》在工业检测、质量追溯等应用场景中,经常需要对产品进行拍照并添加相关信息水印,本文将详细介绍如何使用C#实现一个高性能的拍照和水印添加功能,包含完整的代码实现... 目录1. 概述2. 功能架构设计3. 核心代码实现python3.1 主拍照方法3.2 安全HBIT

录音功能在哪里? 电脑手机等设备打开录音功能的技巧

《录音功能在哪里?电脑手机等设备打开录音功能的技巧》很多时候我们需要使用录音功能,电脑和手机这些常用设备怎么使用录音功能呢?下面我们就来看看详细的教程... 我们在会议讨论、采访记录、课堂学习、灵感创作、法律取证、重要对话时,都可能有录音需求,便于留存关键信息。下面分享一下如何在电脑端和手机端上找到录音功能