dubbo負載均衡之RoundRobin

承接上文,本文繼續(xù)來看dubbo的加權(quán)RoundRobin負載均衡策略。先大概了解一下RoundRobin纷纫,加權(quán)RoundRobin就是按照節(jié)點(服務(wù)節(jié)點叁扫、存儲節(jié)點等)權(quán)重三妈,將請求分發(fā)到不同節(jié)點如下所示:

考慮有三個節(jié)點 A(5)、B(1)莫绣、C(1),括號內(nèi)是該節(jié)點的服務(wù)負載能力畴蒲,假設(shè)有10個請求(R),下面是普通RoundRobin的做法

R1 -> A 对室, R2 -> v 模燥,R3 -> A ,R4 -> A 掩宜, R5 -> A 
R6 -> B
R7 -> C 
可以看到蔫骂,請求會按照權(quán)重分配到不同的節(jié)點。但是考慮一種情況锭亏,如果把請求量級放大到10^n,此時70%請求
會連續(xù)打到節(jié)點A纠吴,而其他節(jié)點則0請求;可能A節(jié)點被打掛慧瘤,流量也不會到BC節(jié)點戴已,不符合負載均衡的初衷固该。

那么,有沒有一種方式糖儡,可以讓請求平均但不連續(xù)的打到某一個節(jié)點伐坏?這就是下面要引出的平滑權(quán)重RoundRobin(比如nginx采用的負載均衡),下面來看下這種策略的實現(xiàn)方式:

單次請求握联,選擇策略:
1桦沉、選取所有節(jié)點中權(quán)重最大的節(jié)點(curMax)
2、更新當前權(quán)重最大節(jié)點的權(quán)重金闽,節(jié)點新權(quán)重(curMaxNew) = 節(jié)點當前權(quán)重(curMax) - 所有節(jié)點當前權(quán)重之和(total)
3纯露、所有節(jié)點權(quán)重更新,節(jié)點新權(quán)重(curNew) = 節(jié)點當前權(quán)重(cur) + 節(jié)點初始權(quán)重(init)
結(jié)束一次請求選擇過程代芜。

用代碼描述可能更清晰一點:

//初始化節(jié)點權(quán)重map
static{
        MAP.put("A",5);
        MAP.put("B",1);
        MAP.put("C",1);
}

/**
* 平滑加權(quán)輪詢
**/
static List<String> smoothRoundRobin(Map<String,Integer> candidateMap,int requestCount){
        Map<String,Integer> currentRoundMap = new HashMap<>(candidateMap);
        Integer sumWeight = candidateMap.entrySet().stream().mapToInt(value -> value.getValue()).sum();

        List<String> resultList = new ArrayList<>();
        for(int i=0;i<requestCount;i++){
            //當前權(quán)重最大的節(jié)點key,例如埠褪,初始是5
            String currentMaxWeight = currentMaxWeight(currentRoundMap);
            //選中,放入結(jié)果
            resultList.add(currentMaxWeight);
            //更新當前權(quán)重最大節(jié)點的權(quán)重挤庇;當前權(quán)重最大節(jié)點權(quán)重- 總權(quán)重
            currentRoundMap.put(currentMaxWeight,currentRoundMap.get(currentMaxWeight) - sumWeight);
            //權(quán)重重新分配钞速;當前每個節(jié)點權(quán)重 + 初始每個節(jié)點權(quán)重
            reRoundMapValue(currentRoundMap,MAP);
        }
        return resultList;
}

/**
* 輔助方法,尋找當前權(quán)重值最大節(jié)點
**/
static String currentMaxWeight(Map<String,Integer> candidateMap){
        List<Integer> weightList = new ArrayList<>(candidateMap.values());

        weightList.sort(Integer::compareTo);
        int maxWeight = weightList.get(weightList.size() - 1);
        for(Map.Entry<String,Integer> entry : candidateMap.entrySet()){
            if(entry.getValue() == maxWeight){
                return entry.getKey();
            }
        }
        return "";
}

/**
* 所有節(jié)點權(quán)重重置
**/
static void reRoundMapValue(Map<String,Integer> roundMap,Map<String,Integer> initialCandidateMap){
        roundMap.forEach((candidate,currentWeight) ->{
            currentWeight += initialCandidateMap.get(candidate);
            roundMap.put(candidate,currentWeight);
        });
}

//執(zhí)行結(jié)果:A->A->B->A->C->A->A
public static void main(String[] args) {
        List<String> roundRobinResult = smoothRoundRobin(MAP,7);
        System.out.println(StringUtils.join(roundRobinResult,"->"));
}

可以看到嫡秕,上面的策略能夠一定程度上保證請求不會持續(xù)打在一個節(jié)點上渴语,相對平均。dubbo的RoundRobin其實參考了nginx的負載均衡昆咽,邏輯類似驾凶,下面來看下dubbo的實現(xiàn)

// 權(quán)重實體,封裝了初始權(quán)重掷酗、當前權(quán)重以及上次更新時間狭郑;普通getter、setter方法省略汇在;
// 注意,這里除了權(quán)重值意外脏答,沒有invoker的相關(guān)信息
protected static class WeightedRoundRobin {
    private int weight;
    private AtomicLong current = new AtomicLong(0);
    private long lastUpdate;
   
    public void setWeight(int weight) {
        this.weight = weight;
        current.set(0);
    }
    public long increaseCurrent() {
        return current.addAndGet(weight);
    }
    public void sel(int total) {
        current.addAndGet(-1 * total);
    }
}

//權(quán)重實體緩存map糕殉,結(jié)構(gòu) <serviceKey.methodName,<URL.identity,權(quán)重實體>
private ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<String, ConcurrentMap<String, WeightedRoundRobin>>();
//權(quán)重更新鎖
private AtomicBoolean updateLock = new AtomicBoolean();

/**
* 核心select方法
**/
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
            //方法級負載均衡
        String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
        ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key);
        if (map == null) {
            methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>());
            map = methodWeightMap.get(key);
        }
        int totalWeight = 0;
        //這里就很靈性了,保證后期maxCurrent值不會溢出殖告。
        long maxCurrent = Long.MIN_VALUE;
        long now = System.currentTimeMillis();
        Invoker<T> selectedInvoker = null;
        WeightedRoundRobin selectedWRR = null;
        // 遍歷所有invoker阿蝶,為每個invoker封裝一個WeightRoundRobin實體;
        for (Invoker<T> invoker : invokers) {
            // methodWeightMap的內(nèi)層map黄绩,key是url唯一標識
            String identifyString = invoker.getUrl().toIdentityString();
            WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
            //調(diào)用基類權(quán)重計算方法初始化權(quán)重
            int weight = getWeight(invoker, invocation);

            if (weightedRoundRobin == null) {
                weightedRoundRobin = new WeightedRoundRobin();
                weightedRoundRobin.setWeight(weight);
                map.putIfAbsent(identifyString, weightedRoundRobin);
            }
            if (weight != weightedRoundRobin.getWeight()) {
                //weight changed,current置0
                weightedRoundRobin.setWeight(weight);
            }
            long cur = weightedRoundRobin.increaseCurrent();
            weightedRoundRobin.setLastUpdate(now);
            //初始maxCurrent為0羡洁,選組權(quán)重值最大的invoker
            if (cur > maxCurrent) {
                maxCurrent = cur
                selectedInvoker = invoker;
                selectedWRR = weightedRoundRobin;
            }
            totalWeight += weight;
        }
        // 這里做了優(yōu)化,invokers.size與map大小不一致爽丹,這時候意味著有的節(jié)點可能掛掉了需要剔除筑煮,重制RoundRobin實體
        // 新增一個updateTime用于限時更新methodWeightMap;
        // 更新策略:超過循環(huán)周期60s的節(jié)點
        if (!updateLock.get() && invokers.size() != map.size()) {
            if (updateLock.compareAndSet(false, true)) {
                try {
                    // copy -> modify -> update reference
                    ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<String, WeightedRoundRobin>();
                    newMap.putAll(map);
                    Iterator<Entry<String, WeightedRoundRobin>> it = newMap.entrySet().iterator();
                    while (it.hasNext()) {
                        Entry<String, WeightedRoundRobin> item = it.next();
                        if (now - item.getValue().getLastUpdate() > RECYCLE_PERIOD) {
                            it.remove();
                        }
                    }
                    methodWeightMap.put(key, newMap);
                } finally {
                    updateLock.set(false);
                }
            }
        }
            
        //一次選擇結(jié)束辛蚊,重置該WeightedRoundRobin權(quán)重( 新權(quán)重 = 當前權(quán)重 - 總權(quán)重),然后返回真仲。
        if (selectedInvoker != null) {
            selectedWRR.sel(totalWeight);
            return selectedInvoker;
        }
        // should not happen here
        return invokers.get(0);
    }

dubbo的負載均衡是方法級的袋马,核心邏輯如下:

  1. 初次select時,針對每一個method的invoker秸应,初始化invoker權(quán)重
  2. 實例化WeightedRoundRobin并放入緩存虑凛;后續(xù)會根據(jù)invoker.gerUrl.identify獲取緩存的weightRoundRobin實體,在此基礎(chǔ)上做權(quán)重更新软啼;
  3. 每次select cur 自增(cur += weight),同時更新update時間戳桑谍;
  4. 選中cur最大的invoker作為返回結(jié)果,返回前會重置該WeightedRoundRobin的cur值祸挪;
  5. dubbo在實際計算過程中加了一個超時時間锣披,如果當前時間戳 - 更新時間 > 超時時間,則認為該節(jié)點可能掛掉了匕积,直接從列表剔除盈罐,下一次select會重新初始化。

注:參考 dubbo源碼版本 2.7.1闪唆,歡迎指正盅粪。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市悄蕾,隨后出現(xiàn)的幾起案子票顾,更是在濱河造成了極大的恐慌,老刑警劉巖帆调,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件奠骄,死亡現(xiàn)場離奇詭異,居然都是意外死亡番刊,警方通過查閱死者的電腦和手機含鳞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來芹务,“玉大人蝉绷,你說我怎么就攤上這事≡姹В” “怎么了熔吗?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長佳晶。 經(jīng)常有香客問我桅狠,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任中跌,我火速辦了婚禮咨堤,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘晒他。我一直安慰自己吱型,他們只是感情好,可當我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布陨仅。 她就那樣靜靜地躺著津滞,像睡著了一般。 火紅的嫁衣襯著肌膚如雪灼伤。 梳的紋絲不亂的頭發(fā)上触徐,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天,我揣著相機與錄音狐赡,去河邊找鬼撞鹉。 笑死,一個胖子當著我的面吹牛颖侄,可吹牛的內(nèi)容都是我干的鸟雏。 我是一名探鬼主播,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼览祖,長吁一口氣:“原來是場噩夢啊……” “哼孝鹊!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起展蒂,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤又活,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后锰悼,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體柳骄,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年箕般,在試婚紗的時候發(fā)現(xiàn)自己被綠了耐薯。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡丝里,死狀恐怖可柿,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情丙者,我是刑警寧澤,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布营密,位于F島的核電站械媒,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜纷捞,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一痢虹、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧主儡,春花似錦奖唯、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至寂汇,卻和暖如春病往,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背骄瓣。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工停巷, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人榕栏。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓畔勤,卻偏偏與公主長得像,于是被迫代替她去往敵國和親扒磁。 傳聞我的和親對象是個殘疾皇子庆揪,可洞房花燭夜當晚...
    茶點故事閱讀 44,955評論 2 355