五、Eureka服务注册、续约、剔除、下线源码分析

2024-01-05 18:40

本文主要是介绍五、Eureka服务注册、续约、剔除、下线源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Eureka 概念的理解

1 服务的注册

当项目启动时(eureka 的客户端),就会向 eureka-server 发送自己的元数据(原始数据)(运行的 ip,端口 port,健康的状态监控等,因为使用的是 http/ResuFul 请求风格),eureka-server 会在自己内部保留这些元数据(内存中)。(有一个服务列表)(restful 风
格,以 http 动词的请求方式,完成对 url 资源的操作)

2 服务的续约

项目启动成功了,除了向 eureka-server 注册自己成功,还会定时的向 eureka-server 汇报自己,心跳,表示自己还活着。(修改一个时间)

3 服务的下线(主动下线)

当项目关闭时,会给 eureka-server 报告,说明自己要下机了。

4 服务的剔除(被动下线,主动剔除)

当项目超过了指定时间没有向 eureka-server 汇报自己,那么 eureka-server 就会认为此节点死掉了,会把它剔除掉,也不会放流量和请求到此节点了。

Eureka 源码分析

为什么要学源码? 答:了解他的原理 出了问题排查 bug,优化你的代码

1 Eureka 运作原理的特点

Eureka-server 对外提供的是 restful 风格的服务以 http 动词的形式对 url 资源进行操作 get post put delete

http 服务 + 特定的请求方式 + 特定的 url 地址

只要利用这些 restful 我们就能对项目实现注册和发现,只不过,eureka 已经帮我们使用 java 语言写了 client,让我们的项目只要依赖 client 就能实现注册和发现!
只要你会发起 Http 请求,那你就有可能自己实现服务的注册和发现。不管你是什么语言!

2 服务注册的源码分析【重点】

在这里插入图片描述

2.1 Eureka-client 发起注册请求

2.1.1 源码位置

在这里插入图片描述

2.1.2如何发送信息注册自己

在这里插入图片描述

2.1.3 真正的注册 AbstractJerseyEurekaHttpClient

在这里插入图片描述
总结:

当 eureka 启动的时候,会向我们指定的 serviceUrl 发送请求,把自己节点的数据以 post
请求的方式,数据以 json 形式发送过去。 当返回的状态码为 204 的时候,表示注册成功。

2.2 Eureka-server 实现注册+保存

2.2.1 接受客户端的请求

com.netflix.eureka.resources.ApplicationResource
在这里插入图片描述

2.2.2 源码位置

在这里插入图片描述

2.2.3 接受 client 的注册请求

在这里插入图片描述

2.2.4 处理请求(注册自己,向其他节点注册)

在这里插入图片描述

2.2.5 真正的注册自己

在这里插入图片描述

2.2.6 具体源码分析

public void register(InstanceInfo registrant, int leaseDuration, boolean isReplication) {try {read.lock();//通过服务名称得到注册的实例Map<String, Lease<InstanceInfo>> gMap = registry.get(registrant.getAppName());REGISTER.increment(isReplication);//因为之前没有实例,肯定为 nullif (gMap == null) {//新建一个集合来存放实例final ConcurrentHashMap<String, Lease<InstanceInfo>> gNewMap = newConcurrentHashMap<String, Lease<InstanceInfo>>();gMap = registry.putIfAbsent(registrant.getAppName(), gNewMap);if (gMap == null) {gMap = gNewMap;}
}//gMap 就是该服务的实例Lease<InstanceInfo> existingLease = gMap.get(registrant.getId());
// Retain the last dirty timestamp without overwriting it, if there is already a lease
if (existingLease != null && (existingLease.getHolder() != null)) {Long existingLastDirtyTimestamp =existingLease.getHolder().getLastDirtyTimestamp();Long registrationLastDirtyTimestamp = registrant.getLastDirtyTimestamp();logger.debug("Existing lease found (existing={}, provided={}",existingLastDirtyTimestamp, registrationLastDirtyTimestamp);// this is a > instead of a >= because if the timestamps are equal, we still take the remote transmitted
// InstanceInfo instead of the server local copy.if (existingLastDirtyTimestamp > registrationLastDirtyTimestamp) {logger.warn("There is an existing lease and the existing lease's dirty timestamp
{} is greater" +
" than the one that is being registered {}", existingLastDirtyTimestamp,
registrationLastDirtyTimestamp);
logger.warn("Using the existing instanceInfo instead of the new instanceInfo as
the registrant");
registrant = existingLease.getHolder();
}
} else {
// The lease does not exist and hence it is a new registration
synchronized (lock) {
if (this.expectedNumberOfClientsSendingRenews > 0) {
// Since the client wants to register it, increase the number of clients
sending renews
this.expectedNumberOfClientsSendingRenews =
this.expectedNumberOfClientsSendingRenews + 1;
updateRenewsPerMinThreshold();
}
}
logger.debug("No previous lease information found; it is new registration");
}//新建一个服务的实例节点Lease<InstanceInfo> lease = new Lease<InstanceInfo>(registrant, leaseDuration);if (existingLease != null) {
lease.setServiceUpTimestamp(existingLease.getServiceUpTimestamp());
}//放到注册 map 的列表里gMap.put(registrant.getId(), lease);recentRegisteredQueue.add(new Pair<Long, String>(
System.currentTimeMillis(),
registrant.getAppName() + "(" + registrant.getId() + ")"));
// This is where the initial state transfer of overridden status happens
if (!InstanceStatus.UNKNOWN.equals(registrant.getOverriddenStatus())) {
logger.debug("Found overridden status {} for instance {}. Checking to see if needs
to be add to the "
+ "overrides", registrant.getOverriddenStatus(),
registrant.getId());
if (!overriddenInstanceStatusMap.containsKey(registrant.getId())) {
logger.info("Not found overridden id {} and hence adding it",
registrant.getId());
overriddenInstanceStatusMap.put(registrant.getId(),
registrant.getOverriddenStatus());
}
}
InstanceStatus overriddenStatusFromMap =
overriddenInstanceStatusMap.get(registrant.getId());
if (overriddenStatusFromMap != null) {
logger.info("Storing overridden status {} from map", overriddenStatusFromMap);
registrant.setOverriddenStatus(overriddenStatusFromMap);
}
// Set the status based on the overridden status rules
InstanceStatus overriddenInstanceStatus = getOverriddenInstanceStatus(registrant,
existingLease, isReplication);
registrant.setStatusWithoutDirty(overriddenInstanceStatus);
// If the lease is registered with UP status, set lease service up timestamp
if (InstanceStatus.UP.equals(registrant.getStatus())) {
lease.serviceUp();
}
registrant.setActionType(ActionType.ADDED);
recentlyChangedQueue.add(new RecentlyChangedItem(lease));//设置心跳时间等参数registrant.setLastUpdatedTimestamp();
invalidateCache(registrant.getAppName(),
registrant.getSecureVipAddress());
logger.info("Registered instance {}/{} with status {} (replication={})",
registrant.getAppName(), registrant.getId(), registrant.getStatus(),
isReplication);
} finally {
read.unlock();
}
}

2.3 服务注册总结

重要的类:

DiscoveryClient 里面的 register()方法完后注册的总体构造

AbstractJerseyEurekaHttpClient 里面的 register()方法具体发送注册请求(post)

InstanceRegistry 里面 register()方法接受客户端的注册请求

PeerAwareInstanceRegistryImpl 里面调用父类的 register()方法实现注册

AbstractInstanceRegistry 里面的 register()方法完成具体的注册保留数据到 map 集合

保存服务实例数据的集合:

第一个 key 是应用名称(全大写) spring.application.name
Value 中的 key 是应用的实例 id eureka.instance.instance-id
Value 中的 value 是 具体的服务节点信息

private final ConcurrentHashMap<String, Map<String,Lease<InstanceInfo>>> registry= new ConcurrentHashMap<String, Map<String,Lease<InstanceInfo>>>();

3 服务续约的源码分析

3.1 Eureka-client 发起续约请求

3.1.1 如何发请求续约自己

DiscoveryClient 的 renew()方法
在这里插入图片描述

3.1.2 真正的请求续约自己(AbstractJerseyEurekaHttpClient)

在这里插入图片描述

3.2 Eureka-server 实现续约操作

3.2.1 接受续约的请求

在这里插入图片描述

3.2.2 真正的续约

在这里插入图片描述

3.2.3 续约的本质

续约的本质就是修改了服务节点的最后更新时间
在这里插入图片描述
duration:代表注册中心最长的忍耐时间:
并不是 30s 没有续约就里面剔除,而是 30 +duration(默认是 90s) 期间内没有续约,才剔除服务

在这里插入图片描述
Volatile 标识的变量是具有可见性的,当一条线程修改了我的剔除时间,其他线程就可以立马看到(应用场景:一写多读),后面在剔除里面有一个定时任务,去检查超时从而判断某一个服务是否应该被剔除。

4 服务剔除的源码分析(被动下线)

4.1 Eureka-server 实现服务剔除

4.1.1 在 AbstractInstanceRegistry 的 evict()方法中筛选剔除的节点

public void evict(long additionalLeaseMs) {
logger.debug("Running the evict task");
if (!isLeaseExpirationEnabled()) {
logger.debug("DS: lease expiration is currently disabled.");
return;
}
// We collect first all expired items, to evict them in random order. For large
eviction sets,
// if we do not that, we might wipe out whole apps before self preservation kicks
in. By randomizing it,
// the impact should be evenly distributed across all applications.
//创建一个新的集合来存放过期的服务实例List<Lease<InstanceInfo>> expiredLeases = new ArrayList<>();
for (Entry<String, Map<String, Lease<InstanceInfo>>> groupEntry :
registry.entrySet()) {
Map<String, Lease<InstanceInfo>> leaseMap = groupEntry.getValue();
if (leaseMap != null) {
//循环for (Entry<String, Lease<InstanceInfo>> leaseEntry :
leaseMap.entrySet()) {
Lease<InstanceInfo> lease = leaseEntry.getValue();
//判断过期,加入集合中if (lease.isExpired(additionalLeaseMs) && lease.getHolder() != null)
{expiredLeases.add(lease);}
}
}
}
// To compensate for GC pauses or drifting local time, we need to use current
registry size as a base for
// triggering self-preservation. Without that we would wipe out full registry.
int registrySize = (int) getLocalRegistrySize();
int registrySizeThreshold = (int) (registrySize *
serverConfig.getRenewalPercentThreshold());
int evictionLimit = registrySize - registrySizeThreshold;
int toEvict = Math.min(expiredLeases.size(), evictionLimit);
if (toEvict > 0) {
logger.info("Evicting {} items (expired={}, evictionLimit={})", toEvict,
expiredLeases.size(), evictionLimit);
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < toEvict; i++) {
// Pick a random item (Knuth shuffle algorithm)
int next = i + random.nextInt(expiredLeases.size() - i);
Collections.swap(expiredLeases, i, next);
Lease<InstanceInfo> lease = expiredLeases.get(i);
String appName = lease.getHolder().getAppName();
String id = lease.getHolder().getId();
EXPIRED.increment();
logger.warn("DS: Registry: expired lease for {}/{}", appName, id);
//这整个方法并没有真的杀死过期的服务节点//下面这个方法才是真正干掉过期的服务internalCancel(appName, id, false);}
}
}

4.1.2 在 internalCancel 方法里面真正实现剔除

在这里插入图片描述

4.1.3 在服务剔除中涉及到哪些重要的点

怎么删除一个集合里面过期的数据?

Redis 怎么清除过期的 key LRU(热点 key)

1 定时(k-thread)

2 惰性 (在再次访问该 key 时有作用)

3 定期 (使用一个线程来完成清除任务)

定期(实时性差) + 惰性

4.1.4 什么时候执行服务剔除操作呢?

查看 evict()方法在哪里调用的
在这里插入图片描述
具体查看多久执行一次呢?
在这里插入图片描述
发现默认是 60s 执行一次
在这里插入图片描述
当然我们也可以自定义检测定时器的执行时间

在这里插入图片描述

服务下线的源码分析

5.1 Eureka-client 发起下线请求

5.1.1 如何发起下线请求

在这里插入图片描述

5.1.2 真正的发请求下线 AbstractJerseyEurekaHttpClient

在这里插入图片描述

5.2 Eureka-server 处理下线请求

5.2.1 接受下线请求

在这里插入图片描述

5.2.2 真正的下线服务

在这里插入图片描述

这篇关于五、Eureka服务注册、续约、剔除、下线源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Python主动抛出异常的各种用法和场景分析

《Python主动抛出异常的各种用法和场景分析》在Python中,我们不仅可以捕获和处理异常,还可以主动抛出异常,也就是以类的方式自定义错误的类型和提示信息,这在编程中非常有用,下面我将详细解释主动抛... 目录一、为什么要主动抛出异常?二、基本语法:raise关键字基本示例三、raise的多种用法1. 抛

github打不开的问题分析及解决

《github打不开的问题分析及解决》:本文主要介绍github打不开的问题分析及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、找到github.com域名解析的ip地址二、找到github.global.ssl.fastly.net网址解析的ip地址三

Mysql的主从同步/复制的原理分析

《Mysql的主从同步/复制的原理分析》:本文主要介绍Mysql的主从同步/复制的原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录为什么要主从同步?mysql主从同步架构有哪些?Mysql主从复制的原理/整体流程级联复制架构为什么好?Mysql主从复制注意

java -jar命令运行 jar包时运行外部依赖jar包的场景分析

《java-jar命令运行jar包时运行外部依赖jar包的场景分析》:本文主要介绍java-jar命令运行jar包时运行外部依赖jar包的场景分析,本文给大家介绍的非常详细,对大家的学习或工作... 目录Java -jar命令运行 jar包时如何运行外部依赖jar包场景:解决:方法一、启动参数添加: -Xb

Apache 高级配置实战之从连接保持到日志分析的完整指南

《Apache高级配置实战之从连接保持到日志分析的完整指南》本文带你从连接保持优化开始,一路走到访问控制和日志管理,最后用AWStats来分析网站数据,对Apache配置日志分析相关知识感兴趣的朋友... 目录Apache 高级配置实战:从连接保持到日志分析的完整指南前言 一、Apache 连接保持 - 性

Linux中的more 和 less区别对比分析

《Linux中的more和less区别对比分析》在Linux/Unix系统中,more和less都是用于分页查看文本文件的命令,但less是more的增强版,功能更强大,:本文主要介绍Linu... 目录1. 基础功能对比2. 常用操作对比less 的操作3. 实际使用示例4. 为什么推荐 less?5.

spring-gateway filters添加自定义过滤器实现流程分析(可插拔)

《spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔)》:本文主要介绍spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔),本文通过实例图... 目录需求背景需求拆解设计流程及作用域逻辑处理代码逻辑需求背景公司要求,通过公司网络代理访问的请求需要做请

Java集成Onlyoffice的示例代码及场景分析

《Java集成Onlyoffice的示例代码及场景分析》:本文主要介绍Java集成Onlyoffice的示例代码及场景分析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 需求场景:实现文档的在线编辑,团队协作总结:两个接口 + 前端页面 + 配置项接口1:一个接口,将o

IDEA下"File is read-only"可能原因分析及"找不到或无法加载主类"的问题

《IDEA下Fileisread-only可能原因分析及找不到或无法加载主类的问题》:本文主要介绍IDEA下Fileisread-only可能原因分析及找不到或无法加载主类的问题,具有很好的参... 目录1.File is read-only”可能原因2.“找不到或无法加载主类”问题的解决总结1.File