获取大致流程
客户端获取服务
前面讲了服务注册,续约,现在还有个获取服务,也是初始化的时候开启的调度任务CacheRefreshThread
:
DiscoveryClient的refreshRegistry刷新注册表
核心方法就是fetchRegistry
。
void refreshRegistry() {
try {
boolean remoteRegionsModified = false;
...
boolean success = fetchRegistry(remoteRegionsModified);
..
} catch (Throwable e) {
logger.error("Cannot fetch registry from server", e);
}
}
fetchRegistry
主要思想就是先判断是增量拉去还是全量拉去,一般一开始就全量拉去,后面是增量,毕竟增量效率高啊。最后获取完信息后比对一下AppsHashCode,也就是比对数据的完整性,保证拉去的信息和注册中心的是一致的。
private boolean fetchRegistry(boolean forceFullRegistryFetch) {
...
try {
// If the delta is disabled or if it is the first time, get all
// applications
Applications applications = getApplications();//获取已在本地的服务
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
{
...
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 {
...
}
...
return true;
}
getAndStoreFullRegistry全量获取
主要还是调用jersey
的,最终到AbstractJerseyEurekaHttpClient
的getApplicationsInternal
,获取后方本地缓存localRegionApps
。
最后是这里:
getAndUpdateDelta增量获取
其实就是调用jersey的增量获取接口,获取增量后判断,如果是null
的话说明有问题,就进行一次全量获取,如果有增量,就进行更新,并比对数据一致性的AppsHashCode
,如果有问题就进行全量获取reconcileAndLogDifference
。
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) {
//如果增量为null,就进行一次全量
getAndStoreFullRegistry();
} else if (fetchRegistryGeneration.compareAndSet(currentUpdateGeneration, currentUpdateGeneration + 1)) {
String reconcileHashCode = "";
if (fetchRegistryUpdateLock.tryLock()) {
try {
updateDelta(delta);//更新增量
reconcileHashCode = getReconcileHashCode(applications);//获取数据一致的AppsHashCode
} finally {
fetchRegistryUpdateLock.unlock();
}
} else {
}
// There is a diff in number of instances for some reason
if (!reconcileHashCode.equals(delta.getAppsHashCode()) || clientConfig.shouldLogDeltaDiff()) {//比对AppsHashCode,如果不一致说明有问题,进行一次全量获取
reconcileAndLogDifference(delta, reconcileHashCode); // this makes a remoteCall
}
} else {
}
}
细节下篇说吧。
好了,今天就到这里了,希望对学习理解有帮助,大神看见勿喷,仅为自己的学习理解,能力有限,请多包涵。