【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

相关文章

Android使用ImageView.ScaleType实现图片的缩放与裁剪功能

《Android使用ImageView.ScaleType实现图片的缩放与裁剪功能》ImageView是最常用的控件之一,它用于展示各种类型的图片,为了能够根据需求调整图片的显示效果,Android提... 目录什么是 ImageView.ScaleType?FIT_XYFIT_STARTFIT_CENTE

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

Android实现两台手机屏幕共享和远程控制功能

《Android实现两台手机屏幕共享和远程控制功能》在远程协助、在线教学、技术支持等多种场景下,实时获得另一部移动设备的屏幕画面,并对其进行操作,具有极高的应用价值,本项目旨在实现两台Android手... 目录一、项目概述二、相关知识2.1 MediaProjection API2.2 Socket 网络

Redis消息队列实现异步秒杀功能

《Redis消息队列实现异步秒杀功能》在高并发场景下,为了提高秒杀业务的性能,可将部分工作交给Redis处理,并通过异步方式执行,Redis提供了多种数据结构来实现消息队列,总结三种,本文详细介绍Re... 目录1 Redis消息队列1.1 List 结构1.2 Pub/Sub 模式1.3 Stream 结

MySQL索引的优化之LIKE模糊查询功能实现

《MySQL索引的优化之LIKE模糊查询功能实现》:本文主要介绍MySQL索引的优化之LIKE模糊查询功能实现,本文通过示例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前缀匹配优化二、后缀匹配优化三、中间匹配优化四、覆盖索引优化五、减少查询范围六、避免通配符开头七、使用外部搜索引擎八、分

Android实现悬浮按钮功能

《Android实现悬浮按钮功能》在很多场景中,我们希望在应用或系统任意界面上都能看到一个小的“悬浮按钮”(FloatingButton),用来快速启动工具、展示未读信息或快捷操作,所以本文给大家介绍... 目录一、项目概述二、相关技术知识三、实现思路四、整合代码4.1 Java 代码(MainActivi

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

SpringBoot实现微信小程序支付功能

《SpringBoot实现微信小程序支付功能》小程序支付功能已成为众多应用的核心需求之一,本文主要介绍了SpringBoot实现微信小程序支付功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作... 目录一、引言二、准备工作(一)微信支付商户平台配置(二)Spring Boot项目搭建(三)配置文件