Eureka系列(三)获取服务Client端具体实现
获取服务Client 端流程
我们先看下面这张图片,这张图片简单描述了下我们Client是如何获取到Server已续约实例信息的流程: 从图片中我们可以知晓大致流程就是Client会自己开启一个定时任务,然后根据不同的条件去调用Server端接口得到所有已续约服务的信息,然后合并到自己的缓存数据中。下面我们详情了解下上述流程在源码中的具体实现。
获取服务Client端源码分析
我们先来看看服务获取定时任务的初始化。那我们的服务获取定时任务什么时候会被初始化呢,那肯定是我们启用我们Eureka Client的时候呗,当我们启动Client时,Eureka会先处理相关的配置,然后初始化我们Client的相关信息,我们的定时任务也就是此时进行的初始化,更具体地说我们的服务续约定时任务就是在DiscoveryClient这个类中initScheduledTasks方法中被初始化的。具体代码如下:
private final ScheduledExecutorService scheduler;
private void initScheduledTasks() {
…省略其他代码
// 初始化定时拉取服务注册信息
scheduler.schedule(
new TimedSupervisorTask(
"cacheRefresh",
scheduler,
cacheRefreshExecutor,
registryFetchIntervalSeconds,
TimeUnit.SECONDS,
expBackOffBound,
new CacheRefreshThread()
),
registryFetchIntervalSeconds, TimeUnit.SECONDS);
…省略其他代码
}
由此可见,我们的定时任务其实是Client进行初始化完成的,并且还是使用ScheduledExecutorService线程池来完成我们的定时任务。我们下面就看看CacheRefreshThread这个类是如何实现获取服务的流程:
class CacheRefreshThread implements Runnable {
public void run() {
refreshRegistry();
}
}
不多说,我们接着看refreshRegistry()方法:
@VisibleForTesting
void refreshRegistry() {
…省略部分代码
boolean success = fetchRegistry(remoteRegionsModified); // 获取实例信息
if (success) {
registrySize = localRegionApps.get().size();
lastSuccessfulRegistryFetchTimestamp = System.currentTimeMillis();
}
…省略部分代码
}
这里不做太多解释,我们接着看fetchRegistry()方法:
private boolean fetchRegistry(boolean forceFullRegistryFetch) {
Stopwatch tracer = FETCH_REGISTRY_TIMER.start();
try {
// If the delta is disabled or if it is the first time, get all
// applications
Applications applications = getApplications();
//1. 是否禁用增量更新;
//2. 是否对某个region特别关注;
//3. 外部调用时是否通过入参指定全量更新;
//4. 本地还未缓存有效的服务列表信息;
if (clientConfig.shouldDisableDelta()
|| (!Strings.isNullOrEmpty(clientConfig.getRegistryRefreshSingleVipAddress()))
|| forceFullRegistryFetch
|| (applications == null)
|| (applications.getRegisteredApplications().size() == 0)
|| (applications.getVersion() == -1)) //Client application does not have latest library supporting delta
{
logger.info("Disable delta property : {}", clientConfig.shouldDisableDelta());
logger.info("Single vip registry refresh property : {}", clientConfig.getRegistryRefreshSingleVipAddress());
logger.info("Force full registry fetch : {}", forceFullRegistryFetch);
logger.info("Application is null : {}", (applications == null));
logger.info("Registered Applications size is zero : {}",
(applications.getRegisteredApplications().size() == 0));
logger.info("Application version is -1: {}", (applications.getVersion() == -1));
getAndStoreFullRegistry(); // 全量更新
} else {
getAndUpdateDelta(applications); // 增量更新
}
applications.setAppsHashCode(applications.getReconcileHashCode());
logTotalInstances();
} catch (Throwable e) {
logger.error(PREFIX + "{} - was unable to refresh its cache! status = {}", appPathIdentifier, e.getMessage(), e);
return false;
} finally {
if (tracer != null) {
tracer.stop();
}
}
// Notify about cache refresh before updating the instance remote status
onCacheRefreshed();
// Update remote status based on refreshed data held in the cache
updateInstanceRemoteStatus();
// registry was fetched successfully, so return true
return true;
}
由此可见,fetchRegistry 方法主要是判断我们获取实例信息是进行全量更新还是增量更新。如果条件成立,则我们会进行全量更新,否则则进行批量更新。下面我们简单介绍下getAndStoreFullRegistry() 全量更新、getAndUpdateDelta(applications)批量更新方法:
// 全量更新
private void getAndStoreFullRegistry() throws Throwable {
long currentUpdateGeneration = fetchRegistryGeneration.get();
logger.info("Getting all instance registry info from the eureka server");
Applications apps = null;
EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null
// 调用服务端接口得到全量的实例信息
? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get())
: eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get());
if (httpResponse.getStatusCode() == Status.OK.getStatusCode()) {
// 将实例信息存进Applications
apps = httpResponse.getEntity();
}
logger.info("The response status is {}", httpResponse.getStatusCode());
if (apps == null) {
logger.error("The application is null for some reason. Not storing this information");
} else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
localRegionApps.set(this.filterAndShuffle(apps));
logger.debug("Got full registry with apps hashcode {}", apps.getAppsHashCode());
} else {
logger.warn("Not updating applications as another thread is updating it already");
}
}
getAndStoreFullRegistry() 简单来说就是通过调用Eureka服务端提供的http接口获取到全部实例信息,然后将实例信息存进我们的Applications中。
// 批量更新
private void getAndUpdateDelta(Applications applications) throws Throwable {
long currentUpdateGeneration = fetchRegistryGeneration.get();
Applications delta = null;
// 得到增量的实例信息
EurekaHttpResponse<Applications> httpResponse = eurekaTransport.queryClient.getDelta(remoteRegionsRef.get());
if (httpResponse.getStatusCode() == Status.OK.getStatusCode()) {
delta = httpResponse.getEntity();
}
if (delta == null) { // 如果增量信息为空,则进行一次全量更新
logger.warn("The server does not allow the delta revision to be applied because it is not safe. "
+ "Hence got the full registry.");
getAndStoreFullRegistry();
}
//考虑到多线程同步问题,这里通过CAS来确保请求发起到现在是线程安全的,
//如果这期间fetchRegistryGeneration变了,就表示其他线程也做了类似操作,因此放弃本次响应的数据
else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
logger.debug("Got delta update with apps hashcode {}", delta.getAppsHashCode());
String reconcileHashCode = "";
if (fetchRegistryUpdateLock.tryLock()) {
try {
// 合并增量实例信息
updateDelta(delta);
// 用合并了增量数据之后的本地数据来生成一致性哈希码
reconcileHashCode = getReconcileHashCode(applications);
} finally {
fetchRegistryUpdateLock.unlock();
}
} else {
logger.warn("Cannot acquire update lock, aborting getAndUpdateDelta");
}
// There is a diff in number of instances for some reason
//Eureka server在返回增量更新数据时,也会返回服务端的一致性哈希码,
//理论上每次本地缓存数据经历了多次增量更新后,计算出的一致性哈希码应该是和服务端一致的,
//如果发现不一致,就证明本地缓存的服务列表信息和Eureka server不一致了,需要做一次全量更新
if (!reconcileHashCode.equals(delta.getAppsHashCode()) || clientConfig.shouldLogDeltaDiff()) {
reconcileAndLogDifference(delta, reconcileHashCode); // this makes a remoteCall
}
} else {
logger.warn("Not updating application delta as another thread is updating it already");
logger.debug("Ignoring delta update with apps hashcode {}, as another thread is updating it already", delta.getAppsHashCode());
}
}
getAndUpdateDelta 方法简单来说,就是首先调用Eureka服务端提供的增量信息接口得到增量实例信息,然后进行判断,如果增量为null,为了数据准确性,调用一下全量更新实例接口更新实例信息。如果增量信息不为空,则进行一个cas处理,如果成功,则进行增量信息的合并。最后会再进行一次判断,判断从服务端得到的批量实例信息计算得到的HashCode是否和从服务端得到的实例信息HashCode值是否相等,如果不相等则会调用reconcileAndLogDifference 方法,再次进行全量更新实例信息。下面我们就简单看下reconcileAndLogDifference这个方法:
private void reconcileAndLogDifference(Applications delta, String reconcileHashCode) throws Throwable {
logger.debug("The Reconcile hashcodes do not match, client : {}, server : {}. Getting the full registry",
reconcileHashCode, delta.getAppsHashCode());
RECONCILE_HASH_CODES_MISMATCH.increment();
long currentUpdateGeneration = fetchRegistryGeneration.get();
EurekaHttpResponse<Applications> httpResponse = clientConfig.getRegistryRefreshSingleVipAddress() == null
// 调用服务端接口得到全量的实例信息
? eurekaTransport.queryClient.getApplications(remoteRegionsRef.get())
: eurekaTransport.queryClient.getVip(clientConfig.getRegistryRefreshSingleVipAddress(), remoteRegionsRef.get());
Applications serverApps = httpResponse.getEntity();
if (serverApps == null) {
logger.warn("Cannot fetch full registry from the server; reconciliation failure");
return;
}
if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
localRegionApps.set(this.filterAndShuffle(serverApps));
getApplications().setVersion(delta.getVersion());
logger.debug(
"The Reconcile hashcodes after complete sync up, client : {}, server : {}.",
getApplications().getReconcileHashCode(),
delta.getAppsHashCode());
} else {
logger.warn("Not setting the applications map as another thread has advanced the update generation");
}
}
由此可见,reconcileAndLogDifference方法和我们getAndStoreFullRegistry方法调用的接口一样,都是调用Eureka服务端提供的全量实例信息接口,然后更新我们自己的实例信息。
总的来说,获取服务Client端的执行流程就可以分为以下两步:
1.初始化一个定时任务,默认30s
2.定时任务中根据不同的情况调用不同的方法来更新本地实例缓存信息
在定时任务中获取实例信息我们也可以分为以下几步:
1.判断是否需要全量更新
2.条件成立则进行全量更新
a.将全量更新数据更新到本地缓存中
3.条件不成立则进行批量更新
a.判断批量更新数据是否为空,是则进行一次全量更新
b.将批量更新数据合并到本地缓存中
c.判断批量更新数据计算得到的HashCode是否和服务端传过来的HashCode相等,如果不相等,说明数据有问题,需要进行一次全量更新
Eureka系列(三)获取服务Client端具体实现的更多相关文章
- Eureka系列(四) 获取服务Server端具体实现
获取服务 Server端流程 我们先看下面这张图片,这张图片简单描述了下我们EurekaClient在调用EurekaServer 提供的获取服务Http接口,Server端实现接口执行的大致流程 ...
- [Python Study Notes]CS架构远程访问获取信息--Client端v2.0
更新内容: 1.增加内存信息获取 2.增加电池信息获取 3.增加磁盘信息获取 4.重新布局窗体 5.增加窗体名称 6.增加连接成功之前,不可按压 效果图: '''''''''''''''''''''' ...
- [Python Study Notes]CS架构远程访问获取信息--Client端v1.0
更新内容: 1.添加entry栏默认ip和port口 2.修正退出功能 3.添加退出自动关闭窗口功能 4.优化cpu显示为固定保留两位小数 '''''''''''''''''''''''''''''' ...
- [Python Study Notes]CS架构远程访问获取信息--Client端
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...
- springcloud系列三 搭建服务模块
搭建服务模块为了模拟正式开发环境,只是少写了service层直接在controller里面直接引用,直接上图和代码:更为方便: 创建完成之后加入配置: pom.xml文件: <?xml vers ...
- 第三章 服务治理:Spring Cloud Eureka
Spring Cloud Eureka是Spring Cloud Netflix 微服务套件中的一部分,它基于Netflix Eureka做了二次封装,主要负责完成微服务架构中的服务治理功能.Spri ...
- Eureka系列(二) 服务注册Server端具体实现
服务注册 Server端流程 我们先看下面这张图片,这张图片简单描述了下我们EurekaClient 在调用EurekaServer 提供的服务注册Http接口,Server端实现接口执行的大致流 ...
- SpringCloud系列三:SpringSecurity 安全访问(配置安全验证、服务消费端处理、无状态 Session 配置、定义公共安全配置程序类)
1.概念:SpringSecurity 安全访问 2.具体内容 所有的 Rest 服务最终都是暴露在公网上的,也就是说如果你的 Rest 服务属于一些你自己公司的私人业务,这样的结果会直接 导致你信息 ...
- Spring Cloud微服务笔记(三)服务治理:Spring Cloud Eureka快速入门
服务治理:Spring Cloud Eureka 一.服务治理 服务治理是微服务架构中最为核心和基础的模块,它主要用来实现各个微服务实例的自动化注册与发现. 1.服务注册: 在服务治理框架中,通常会构 ...
随机推荐
- 如何在苹果电脑下载器Folx中管理下载列表
Folx是一款Mas OS专用的下载器,提供了便捷的下载管理.灵活的设置.今天小编准备跟大家聊一聊关于Folx中常见的几种下载管理方式. 一.管理任务状态栏 在Folx下载面板上,可以通过类别查看任务 ...
- FL studio系列教程(十六):FL Studio查看菜单讲解
FL Studio中每个窗口的显示.隐藏和布局命令都在查看菜单中.其中它被分为窗口.布局和浏览器3个部分,各项名称都有其单独的作用.窗口部分主要是软件的显示的一些菜单这里就不详细讲解了,接下来我们重点 ...
- python 如何跳过异常继续执行
使用try...except...语句,类似于if...else...,可以跳过异常继续执行程序,这是Python的优势 用法如下: 1 2 3 4 5 6 try: # 可能会 ...
- php进阶学习-单例设计模式
什么是单例模式(singleton)? 在整个应用程序的生命周期中,任何一个时刻,单例类的实例都只存在一个,同时这个类还必须提供一个访问该类的全局访问点. 单例模式的特点 一个类只有一个实例 私有克隆 ...
- 记录一下超大list引起oom
1.2g的堆内存 比较大的对象20w个,oom
- 网络 华为 ensp 命令
VLAN 端口有三种模式:access,hybrid,trunk. Access类型端口:只能属于1个VLAN,且该端口不打tag,一般用于连接计算机端口: Trunk类型端口:可以允许多个VLAN通 ...
- kali修改配置文件后并保存
vim是进入配置文件并修改 修改完按Esc进入控制模式,再:w保存 :wq是保存并退出
- C#(三)基础篇—方法,递归,条件分支,循环,三元操作符
C# 本随笔为个人复习巩固知识用,多从书上总结与理解得来,如有错误麻烦指正 2020-12-03 1.方法 static void Main(string[] args) { float Sum(fl ...
- 本人的CSDN博客
本人的CSDN博客链接: 传送门
- MySQL——一致性非锁定读(快照读)&MVCC
MySQL--一致性非锁定读(快照读) MySQL数据库中读分为一致性非锁定读.一致性锁定读 一致性非锁定读(快照读),普通的SELECT,通过多版本并发控制(MVCC)实现. 一致性锁定读(当前读) ...