Eureka源碼淺讀---注冊表增量拉取

Eureka源碼采用1.7.2版本

本人小白募判,此文為本人閱讀源碼筆記,如果您讀到本文咒唆,您需要自己甄別是否正確届垫,文中的說明只代表本人理解,不一定是正確的H汀W按Α!

注冊表的增量拉取主要依賴Eureka Client的定時(shí)緩存更新任務(wù),在進(jìn)行new DiscoveryClient()的時(shí)候進(jìn)行了緩存定時(shí)任務(wù)更新的創(chuàng)建浸船。

            //初始化支持緩存刷新的線程池
            cacheRefreshExecutor = new ThreadPoolExecutor(
                    1, clientConfig.getCacheRefreshExecutorThreadPoolSize(), 0, TimeUnit.SECONDS,
                    new SynchronousQueue<Runnable>(),
                    new ThreadFactoryBuilder()
                            .setNameFormat("DiscoveryClient-CacheRefreshExecutor-%d")
                            .setDaemon(true)
                            .build()
            );  // use direct handoff

任務(wù)的初始化在同方法的initScheduledTasks()中

com.netflix.discovery.DiscoveryClient#initScheduledTasks

         //初始化拉取定時(shí)表定時(shí)調(diào)度任務(wù) 30S
        if (clientConfig.shouldFetchRegistry()) {
            // registry cache refresh timer
            int registryFetchIntervalSeconds = clientConfig.getRegistryFetchIntervalSeconds();
            int expBackOffBound = clientConfig.getCacheRefreshExecutorExponentialBackOffBound();
            //定時(shí)抓取增量注冊表
            scheduler.schedule(
                    new TimedSupervisorTask(
                            "cacheRefresh",
                            scheduler,
                            cacheRefreshExecutor,
                            registryFetchIntervalSeconds,
                            TimeUnit.SECONDS,
                            expBackOffBound,
                            //緩存刷新線程
                            new CacheRefreshThread()
                    ),
                    registryFetchIntervalSeconds, TimeUnit.SECONDS);
        }

此定時(shí)任務(wù)默認(rèn)30S執(zhí)行一次增量拉取

com.netflix.discovery.DiscoveryClient#refreshRegistry

最后還是調(diào)用的:

com.netflix.discovery.DiscoveryClient#fetchRegistry

            } else {
                //增量拉取注冊表
                getAndUpdateDelta(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();
        } 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);
                    //計(jì)算合并后的本地注冊表的Hash值
                    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
            //如果合并后本地注冊的Hash值與Server端的全量注冊表的Hash值不相等,則進(jìn)行全量拉取
            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());
        }
    }

先不討論服務(wù)端對(duì)增量拉取的處理邏輯李命,在客戶端登淘,主要處理邏輯如下:

  • http請求獲取增量注冊表信息
  • 判斷增量拉取是否為空,如果為空走一次全量拉取
  • 如果增量拉取不為空封字,合并本地注冊表和拉取的增量注冊表黔州,計(jì)算本地合并后的注冊表耍鬓,將注冊中心的全量注冊表的HashCode與本地合并后的HashCode進(jìn)行比較,如果不相等流妻,走一次全量拉取

接下來我們看看服務(wù)端對(duì)增量拉取的請求處理邏輯

com.netflix.eureka.resources.ApplicationsResource#getContainerDifferential

        //增量拉取的Key ALL_APPS_DELTA
        Key cacheKey = new Key(Key.EntityType.Application,
                ResponseCacheImpl.ALL_APPS_DELTA,
                keyType, CurrentRequestVersion.get(), EurekaAccept.fromString(eurekaAccept), regions
        );

        if (acceptEncoding != null
                && acceptEncoding.contains(HEADER_GZIP_VALUE)) {
            return Response.ok(responseCache.getGZIP(cacheKey))
                    .header(HEADER_CONTENT_ENCODING, HEADER_GZIP_VALUE)
                    .header(HEADER_CONTENT_TYPE, returnMediaType)
                    .build();
        } else {
            return Response.ok(responseCache.get(cacheKey))
                    .build();
        }

可以看出也是走的多級(jí)緩存那一套機(jī)制

com.netflix.eureka.registry.ResponseCacheImpl#getValue

    @VisibleForTesting
    Value getValue(final Key key, boolean useReadOnlyCache) {
        Value payload = null;
        try {
            if (useReadOnlyCache) {
                //readOnlyCacheMap 只讀緩存
                final Value currentPayload = readOnlyCacheMap.get(key);
                if (currentPayload != null) {
                    payload = currentPayload;
                } else {
                    //readWriteCacheMap 讀寫緩存
                    payload = readWriteCacheMap.get(key);
                    //再放入只讀緩存中
                    readOnlyCacheMap.put(key, payload);
                }
            } else {
                payload = readWriteCacheMap.get(key);
            }
        } catch (Throwable t) {
            logger.error("Cannot get value for key :" + key, t);
        }
        return payload;
    }

但是有區(qū)別的是讀寫緩存中牲蜀,緩存重建的方法是不同的

com.netflix.eureka.registry.ResponseCacheImpl#generatePayload

                    } else if (ALL_APPS_DELTA.equals(key.getName())) {
                        if (isRemoteRegionRequested) {
                            tracer = serializeDeltaAppsWithRemoteRegionTimer.start();
                            versionDeltaWithRegions.incrementAndGet();
                            versionDeltaWithRegionsLegacy.incrementAndGet();
                            payload = getPayLoad(key,
                                    registry.getApplicationDeltasFromMultipleRegions(key.getRegions()));
                        } else {
                            tracer = serializeDeltaAppsTimer.start();
                            versionDelta.incrementAndGet();
                            versionDeltaLegacy.incrementAndGet();
                            payload = getPayLoad(key, registry.getApplicationDeltas());
                        }
                    } 

最終指向的是這個(gè)方法

com.netflix.eureka.registry.AbstractInstanceRegistry#getApplicationDeltasFromMultipleRegions

    public Applications getApplicationDeltasFromMultipleRegions(String[] remoteRegions) {
        if (null == remoteRegions) {
            remoteRegions = allKnownRemoteRegions; // null means all remote regions.
        }

        boolean includeRemoteRegion = remoteRegions.length != 0;

        if (includeRemoteRegion) {
            GET_ALL_WITH_REMOTE_REGIONS_CACHE_MISS_DELTA.increment();
        } else {
            GET_ALL_CACHE_MISS_DELTA.increment();
        }

        Applications apps = new Applications();
        apps.setVersion(responseCache.getVersionDeltaWithRegions().get());
        Map<String, Application> applicationInstancesMap = new HashMap<String, Application>();
        try {
            write.lock();
            //獲取到最近修改隊(duì)列中的服務(wù)實(shí)例的 3分鐘內(nèi)變化的實(shí)例
            Iterator<RecentlyChangedItem> iter = this.recentlyChangedQueue.iterator();
            logger.debug("The number of elements in the delta queue is :" + this.recentlyChangedQueue.size());
            while (iter.hasNext()) {
                Lease<InstanceInfo> lease = iter.next().getLeaseInfo();
                InstanceInfo instanceInfo = lease.getHolder();
                Object[] args = {instanceInfo.getId(),
                        instanceInfo.getStatus().name(),
                        instanceInfo.getActionType().name()};
                logger.debug("The instance id %s is found with status %s and actiontype %s", args);
                Application app = applicationInstancesMap.get(instanceInfo.getAppName());
                if (app == null) {
                    app = new Application(instanceInfo.getAppName());
                    applicationInstancesMap.put(instanceInfo.getAppName(), app);
                    apps.addApplication(app);
                }
                app.addInstance(decorateInstanceInfo(lease));
            }

            if (includeRemoteRegion) {
                for (String remoteRegion : remoteRegions) {
                    RemoteRegionRegistry remoteRegistry = regionNameVSRemoteRegistry.get(remoteRegion);
                    if (null != remoteRegistry) {
                        Applications remoteAppsDelta = remoteRegistry.getApplicationDeltas();
                        if (null != remoteAppsDelta) {
                            for (Application application : remoteAppsDelta.getRegisteredApplications()) {
                                if (shouldFetchFromRemoteRegistry(application.getName(), remoteRegion)) {
                                    Application appInstanceTillNow =
                                            apps.getRegisteredApplications(application.getName());
                                    if (appInstanceTillNow == null) {
                                        appInstanceTillNow = new Application(application.getName());
                                        apps.addApplication(appInstanceTillNow);
                                    }
                                    for (InstanceInfo instanceInfo : application.getInstances()) {
                                        appInstanceTillNow.addInstance(instanceInfo);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Applications allApps = getApplicationsFromMultipleRegions(remoteRegions);
            //獲取全量注冊表的Hash值
            apps.setAppsHashCode(allApps.getReconcileHashCode());
            return apps;
        } finally {
            write.unlock();
        }
    }

方法的核心就是兩步

  • 從recentlyChangedQueue獲取到變化實(shí)例,封裝成Applications
  • 計(jì)算當(dāng)前注冊表的HashCode绅这,并賦值給Applications

由此可以看出涣达,客戶端獲取到的增量注冊表就是從recentlyChangedQueue中獲取的。

recentlyChangedQueue 最近修改隊(duì)列证薇,全文搜索下可以發(fā)現(xiàn)度苔,如果出現(xiàn)實(shí)例狀態(tài)變化都會(huì)加入該隊(duì)列中

  1. 注冊
                if (InstanceStatus.UP.equals(registrant.getStatus())) {
                lease.serviceUp();
                    }
                    registrant.setActionType(ActionType.ADDED);
                    //加入到最近修改隊(duì)列中
                    recentlyChangedQueue.add(new RecentlyChangedItem(lease));
                    registrant.setLastUpdatedTimestamp();
  1. 下線\故障移除
                if (instanceInfo != null) {
                    //設(shè)置服務(wù)實(shí)例的行為 刪除
                    instanceInfo.setActionType(ActionType.DELETED);
                    //加入最近修改的隊(duì)列中
                    recentlyChangedQueue.add(new RecentlyChangedItem(leaseToCancel));
                    instanceInfo.setLastUpdatedTimestamp();
                    vip = instanceInfo.getVIPAddress();
                    svip = instanceInfo.getSecureVipAddress();
                }
  1. 狀態(tài)變更
                if (replicaDirtyTimestamp > info.getLastDirtyTimestamp()) {
                        info.setLastDirtyTimestamp(replicaDirtyTimestamp);
                    }
                    info.setActionType(ActionType.MODIFIED);
                    recentlyChangedQueue.add(new RecentlyChangedItem(lease));
                    info.setLastUpdatedTimestamp();

那么recentlyChangedQueue就保存著所有修改的服務(wù)實(shí)例,但是該隊(duì)列的元素也是有有效期的浑度,主要靠定時(shí)過期任務(wù)完成的林螃。

com.netflix.eureka.registry.AbstractInstanceRegistry#AbstractInstanceRegistry

        //初始化心跳計(jì)數(shù)器 和自我保護(hù)機(jī)制相關(guān)
        this.renewsLastMin = new MeasuredRate(1000 * 60 * 1);

        //30s執(zhí)行一次recentlyChangedQueue的清理
        this.deltaRetentionTimer.schedule(getDeltaRetentionTask(),
                serverConfig.getDeltaRetentionTimerIntervalInMs(),
                serverConfig.getDeltaRetentionTimerIntervalInMs());
    //定時(shí)清理recentlyChangedQueue表中的過期變動(dòng)實(shí)例
    private TimerTask getDeltaRetentionTask() {
        return new TimerTask() {

            @Override
            public void run() {
                Iterator<RecentlyChangedItem> it = recentlyChangedQueue.iterator();
                while (it.hasNext()) {
                    //時(shí)間比對(duì) 保留最近3分鐘的數(shù)據(jù) 默認(rèn)
                    if (it.next().getLastUpdateTime() <
                            System.currentTimeMillis() - serverConfig.getRetentionTimeInMSInDeltaQueue()) {
                        it.remove();
                    } else {
                        break;
                    }
                }
            }

        };
    }

默認(rèn)只保留最近3分鐘的變動(dòng)實(shí)例

簡單流程圖

Eureka增量注冊表拉取簡易流程.png

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市俺泣,隨后出現(xiàn)的幾起案子疗认,更是在濱河造成了極大的恐慌,老刑警劉巖伏钠,帶你破解...
    沈念sama閱讀 212,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件横漏,死亡現(xiàn)場離奇詭異,居然都是意外死亡熟掂,警方通過查閱死者的電腦和手機(jī)缎浇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,755評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來赴肚,“玉大人素跺,你說我怎么就攤上這事∮” “怎么了指厌?”我有些...
    開封第一講書人閱讀 158,369評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長踊跟。 經(jīng)常有香客問我踩验,道長,這世上最難降的妖魔是什么商玫? 我笑而不...
    開封第一講書人閱讀 56,799評(píng)論 1 285
  • 正文 為了忘掉前任箕憾,我火速辦了婚禮,結(jié)果婚禮上拳昌,老公的妹妹穿的比我還像新娘袭异。我一直安慰自己,他們只是感情好炬藤,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,910評(píng)論 6 386
  • 文/花漫 我一把揭開白布御铃。 她就那樣靜靜地躺著碴里,像睡著了一般。 火紅的嫁衣襯著肌膚如雪畅买。 梳的紋絲不亂的頭發(fā)上并闲,一...
    開封第一講書人閱讀 50,096評(píng)論 1 291
  • 那天细睡,我揣著相機(jī)與錄音谷羞,去河邊找鬼。 笑死溜徙,一個(gè)胖子當(dāng)著我的面吹牛湃缎,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蠢壹,決...
    沈念sama閱讀 39,159評(píng)論 3 411
  • 文/蒼蘭香墨 我猛地睜開眼嗓违,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了图贸?” 一聲冷哼從身側(cè)響起蹂季,我...
    開封第一講書人閱讀 37,917評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎疏日,沒想到半個(gè)月后偿洁,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,360評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡沟优,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,673評(píng)論 2 327
  • 正文 我和宋清朗相戀三年涕滋,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片挠阁。...
    茶點(diǎn)故事閱讀 38,814評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡宾肺,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出侵俗,到底是詐尸還是另有隱情锨用,我是刑警寧澤,帶...
    沈念sama閱讀 34,509評(píng)論 4 334
  • 正文 年R本政府宣布隘谣,位于F島的核電站黔酥,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏洪橘。R本人自食惡果不足惜跪者,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,156評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望熄求。 院中可真熱鬧渣玲,春花似錦、人聲如沸弟晚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,882評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至枚钓,卻和暖如春铅搓,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背搀捷。 一陣腳步聲響...
    開封第一講書人閱讀 32,123評(píng)論 1 267
  • 我被黑心中介騙來泰國打工星掰, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人嫩舟。 一個(gè)月前我還...
    沈念sama閱讀 46,641評(píng)論 2 362
  • 正文 我出身青樓氢烘,卻偏偏與公主長得像,于是被迫代替她去往敵國和親家厌。 傳聞我的和親對(duì)象是個(gè)殘疾皇子播玖,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,728評(píng)論 2 351

推薦閱讀更多精彩內(nèi)容