Dubbo源碼解析(三十八)集羣——LoadBalance

集羣——LoadBalance

目標:介紹dubbo中集羣的負載均衡,介紹dubbo-cluster下loadBalance包的源碼。

前言

負載均衡,說的通俗點就是要一碗水端平。在這個時代,公平是很重要的,在網絡請求的時候一樣是這個道理,咱們有不少機器,可是請求總是到某個服務器上,而某些服務器又常年空閒,致使了資源的浪費,也增長了服務器由於壓力過載而宕機的風險。這個時候就須要負載均衡的出現。它就至關因而一個天秤,經過各類策略,可讓每臺服務器獲取到適合本身處理能力的負載,這樣既可以爲高負載的服務器分流,還能避免資源浪費。負載均衡分爲軟件的負載均衡和硬件負載均衡,咱們這裏講到的是軟件負載均衡,在dubbo中,須要對消費者的調用請求進行分配,避免少數服務提供者負載過大,其餘服務空閒的狀況,由於負載過大會致使服務請求超時。這個時候就須要負載均衡起做用了。Dubbo 提供了4種負載均衡實現:java

  1. RandomLoadBalance:基於權重隨機算法
  2. LeastActiveLoadBalance:基於最少活躍調用數算法
  3. ConsistentHashLoadBalance:基於 hash 一致性
  4. RoundRobinLoadBalance:基於加權輪詢算法

具體的實現看下面解析。node

源碼分析

(一)AbstractLoadBalance

該類實現了LoadBalance接口,是負載均衡的抽象類,提供了權重計算的功能。git

1.select
@Override
public <T> Invoker<T> select(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    // 若是invokers爲空則返回空
    if (invokers == null || invokers.isEmpty())
        return null;
    // 若是invokers只有一個服務提供者,則返回一個
    if (invokers.size() == 1)
        return invokers.get(0);
    // 調用doSelect進行選擇
    return doSelect(invokers, url, invocation);
}

該方法是選擇一個invoker,關鍵的選擇仍是調用了doSelect方法,不過doSelect是一個抽象方法,由上述四種負載均衡策略來各自實現。github

2.getWeight
protected int getWeight(Invoker<?> invoker, Invocation invocation) {
    // 得到 weight 配置,即服務權重。默認爲 100
    int weight = invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.WEIGHT_KEY, Constants.DEFAULT_WEIGHT);
    if (weight > 0) {
        // 得到啓動時間戳
        long timestamp = invoker.getUrl().getParameter(Constants.REMOTE_TIMESTAMP_KEY, 0L);
        if (timestamp > 0L) {
            // 得到啓動總時長
            int uptime = (int) (System.currentTimeMillis() - timestamp);
            // 得到預熱須要總時長。默認爲10分鐘
            int warmup = invoker.getUrl().getParameter(Constants.WARMUP_KEY, Constants.DEFAULT_WARMUP);
            // 若是服務運行時間小於預熱時間,則從新計算服務權重,即降權
            if (uptime > 0 && uptime < warmup) {
                weight = calculateWarmupWeight(uptime, warmup, weight);
            }
        }
    }
    return weight;
}

該方法是得到權重的方法,計算權重在calculateWarmupWeight方法中實現,該方法考慮到了jvm預熱的過程。算法

3.calculateWarmupWeight
static int calculateWarmupWeight(int uptime, int warmup, int weight) {
    // 計算權重 (uptime / warmup) * weight,進度百分比 * 權重
    int ww = (int) ((float) uptime / ((float) warmup / (float) weight));
    // 權重範圍爲 [0, weight] 之間
    return ww < 1 ? 1 : (ww > weight ? weight : ww);
}

該方法是計算權重的方法,其中計算公式是(uptime / warmup) weight,含義就是進度百分比 權重值。數組

(二)RandomLoadBalance

該類是基於權重隨機算法的負載均衡實現類,咱們先來說講原理,好比我有有一組服務器 servers = [A, B, C],他們他們對應的權重爲 weights = [6, 3, 1],權重總和爲10,如今把這些權重值平鋪在一維座標值上,分別出現三個區域,A區域爲[0,6),B區域爲[6,9),C區域爲[9,10),而後產生一個[0, 10)的隨機數,看該數字落在哪一個區間內,就用哪臺服務器,這樣權重越大的,被擊中的機率就越大。緩存

public class RandomLoadBalance extends AbstractLoadBalance {

    public static final String NAME = "random";

    /**
     * 隨機數產生器
     */
    private final Random random = new Random();

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        // 得到服務長度
        int length = invokers.size(); // Number of invokers
        // 總的權重
        int totalWeight = 0; // The sum of weights
        // 是否有相同的權重
        boolean sameWeight = true; // Every invoker has the same weight?
        // 遍歷每一個服務,計算相應權重
        for (int i = 0; i < length; i++) {
            int weight = getWeight(invokers.get(i), invocation);
            // 計算總的權重值
            totalWeight += weight; // Sum
            // 若是前一個服務的權重值不等於後一個則sameWeight爲false
            if (sameWeight && i > 0
                    && weight != getWeight(invokers.get(i - 1), invocation)) {
                sameWeight = false;
            }
        }
        // 若是每一個服務權重都不一樣,而且總的權重值不爲0
        if (totalWeight > 0 && !sameWeight) {
            // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight.
            int offset = random.nextInt(totalWeight);
            // Return a invoker based on the random value.
            // 循環讓 offset 數減去服務提供者權重值,當 offset 小於0時,返回相應的 Invoker。
            // 舉例說明一下,咱們有 servers = [A, B, C],weights = [6, 3, 1],offset = 7。
            // 第一次循環,offset - 6 = 1 > 0,即 offset > 6,
            // 代表其不會落在服務器 A 對應的區間上。
            // 第二次循環,offset - 3 = -2 < 0,即 6 < offset < 9,
            // 代表其會落在服務器 B 對應的區間上
            for (int i = 0; i < length; i++) {
                offset -= getWeight(invokers.get(i), invocation);
                if (offset < 0) {
                    return invokers.get(i);
                }
            }
        }
        // If all invokers have the same weight value or totalWeight=0, return evenly.
        // 若是全部服務提供者權重值相同,此時直接隨機返回一個便可
        return invokers.get(random.nextInt(length));
    }

}

該算法比較好理解,固然 RandomLoadBalance 也存在必定的缺點,當調用次數比較少時,Random 產生的隨機數可能會比較集中,此時多數請求會落到同一臺服務器上,不過影響不大。服務器

(三)LeastActiveLoadBalance

該負載均衡策略基於最少活躍調用數算法,某個服務活躍調用數越小,代表該服務提供者效率越高,也就代表單位時間內可以處理的請求更多。此時應該選擇該類服務器。實現很簡單,就是每個服務都有一個活躍數active來記錄該服務的活躍值,每收到一個請求,該active就會加1,,沒完成一個請求,active就會減1。在服務運行一段時間後,性能好的服務提供者處理請求的速度更快,所以活躍數降低的也越快,此時這樣的服務提供者可以優先獲取到新的服務請求。除了最小活躍數,還引入了權重值,也就是當活躍數同樣的時候,選擇利用權重法來進行選擇,若是權重也同樣,那麼隨機選擇一個。網絡

public class LeastActiveLoadBalance extends AbstractLoadBalance {

    public static final String NAME = "leastactive";

    /**
     * 隨機器
     */
    private final Random random = new Random();

    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        // 得到服務長度
        int length = invokers.size(); // Number of invokers
        // 最小的活躍數
        int leastActive = -1; // The least active value of all invokers
        // 具備相同「最小活躍數」的服務者提供者(如下用 Invoker 代稱)數量
        int leastCount = 0; // The number of invokers having the same least active value (leastActive)
        // leastIndexs 用於記錄具備相同「最小活躍數」的 Invoker 在 invokers 列表中的下標信息
        int[] leastIndexs = new int[length]; // The index of invokers having the same least active value (leastActive)
        // 總的權重
        int totalWeight = 0; // The sum of with warmup weights
        // 第一個最小活躍數的 Invoker 權重值,用於與其餘具備相同最小活躍數的 Invoker 的權重進行對比,
        // 以檢測是否「全部具備相同最小活躍數的 Invoker 的權重」均相等
        int firstWeight = 0; // Initial value, used for comparision
        // 是否權重相同
        boolean sameWeight = true; // Every invoker has the same weight value?
        for (int i = 0; i < length; i++) {
            Invoker<T> invoker = invokers.get(i);
            // 獲取 Invoker 對應的活躍數
            int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive(); // Active number
            // 得到該服務的權重
            int afterWarmup = getWeight(invoker, invocation); // Weight
            // 發現更小的活躍數,從新開始
            if (leastActive == -1 || active < leastActive) { // Restart, when find a invoker having smaller least active value.
                // 記錄當前最小的活躍數
                leastActive = active; // Record the current least active value
                // 更新 leastCount 爲 1
                leastCount = 1; // Reset leastCount, count again based on current leastCount
                // 記錄當前下標值到 leastIndexs 中
                leastIndexs[0] = i; // Reset
                totalWeight = afterWarmup; // Reset
                firstWeight = afterWarmup; // Record the weight the first invoker
                sameWeight = true; // Reset, every invoker has the same weight value?
                // 若是當前 Invoker 的活躍數 active 與最小活躍數 leastActive 相同
            } else if (active == leastActive) { // If current invoker's active value equals with leaseActive, then accumulating.
                // 在 leastIndexs 中記錄下當前 Invoker 在 invokers 集合中的下標
                leastIndexs[leastCount++] = i; // Record index number of this invoker
                // 累加權重
                totalWeight += afterWarmup; // Add this invoker's weight to totalWeight.
                // If every invoker has the same weight?
                if (sameWeight && i > 0
                        && afterWarmup != firstWeight) {
                    sameWeight = false;
                }
            }
        }
        // assert(leastCount > 0)
        // 當只有一個 Invoker 具備最小活躍數,此時直接返回該 Invoker 便可
        if (leastCount == 1) {
            // If we got exactly one invoker having the least active value, return this invoker directly.
            return invokers.get(leastIndexs[0]);
        }
        // 有多個 Invoker 具備相同的最小活躍數,但它們之間的權重不一樣
        if (!sameWeight && totalWeight > 0) {
            // If (not every invoker has the same weight & at least one invoker's weight>0), select randomly based on totalWeight.
            // 隨機生成一個數字
            int offsetWeight = random.nextInt(totalWeight) + 1;
            // Return a invoker based on the random value.
            // 相關算法能夠參考RandomLoadBalance
            for (int i = 0; i < leastCount; i++) {
                int leastIndex = leastIndexs[i];
                offsetWeight -= getWeight(invokers.get(leastIndex), invocation);
                if (offsetWeight <= 0)
                    return invokers.get(leastIndex);
            }
        }
        // If all invokers have the same weight value or totalWeight=0, return evenly.
        // 若是權重同樣,則隨機取一個
        return invokers.get(leastIndexs[random.nextInt(leastCount)]);
    }
}

前半部分在進行最小活躍數的策略,後半部分在進行權重的隨機策略,能夠參見RandomLoadBalance。app

(四)ConsistentHashLoadBalance

該類是負載均衡基於 hash 一致性的邏輯實現。一致性哈希算法由麻省理工學院的 Karger 及其合做者於1997年提供出的,一開始被大量運用於緩存系統的負載均衡。它的工做原理是這樣的:首先根據 ip 或其餘的信息爲緩存節點生成一個 hash,在dubbo中使用參數進行計算hash。並將這個 hash 投射到 [0, 232 - 1] 的圓環上,當有查詢或寫入請求時,則生成一個 hash 值。而後查找第一個大於或等於該 hash 值的緩存節點,併到這個節點中查詢或寫入緩存項。若是當前節點掛了,則在下一次查詢或寫入緩存時,爲緩存項查找另外一個大於其 hash 值的緩存節點便可。大體效果以下圖所示(引用一下官網的圖)

每一個緩存節點在圓環上佔據一個位置。若是緩存項的 key 的 hash 值小於緩存節點 hash 值,則到該緩存節點中存儲或讀取緩存項,這裏有兩個概念不要弄混,緩存節點就比如dubbo中的服務提供者,會有不少的服務提供者,而緩存項就比如是服務引用的消費者。好比下面綠色點對應的緩存項也就是服務消費者將會被存儲到 cache-2 節點中。因爲 cache-3 掛了,本來應該存到該節點中的緩存項也就是服務消費者最終會存儲到 cache-4 節點中,也就是調用cache-4 這個服務提供者。

consistent-hash

可是在hash一致性算法並不可以保證hash算法的平衡性,就拿上面的例子來看,cache-3掛掉了,那該節點下的全部緩存項都要存儲到 cache-4 節點中,這就致使hash值低的一直往高的存儲,會面臨一個不平衡的現象,見下圖:

consistent-hash-data-incline

能夠看到最後會變成相似不平衡的現象,那咱們應該怎麼避免這樣的事情,作到平衡性,那就須要引入虛擬節點,虛擬節點是實際節點在 hash 空間的複製品,「虛擬節點」在 hash 空間中以hash值排列。好比下圖:

consistent-hash-invoker

能夠看到各個節點都被均勻分佈在圓環上,而某一個服務提供者竟然有多個節點存在,分別跟其餘節點交錯排列,這樣作的目的就是避免數據傾斜問題,也就是因爲節點不夠分散,致使大量請求落到了同一個節點上,而其餘節點只會接收到了少許請求的狀況。相似第二張圖的狀況。

看完原理,接下來咱們來看看代碼

1.doSelect
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    // 得到方法名
    String methodName = RpcUtils.getMethodName(invocation);
    // 得到key
    String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
    // 獲取 invokers 原始的 hashcode
    int identityHashCode = System.identityHashCode(invokers);
    // 從一致性 hash 選擇器集合中得到一致性 hash 選擇器
    ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
    // 若是等於空或者選擇器的hash值不等於原始的值,則新建一個一致性 hash 選擇器,而且加入到集合
    if (selector == null || selector.identityHashCode != identityHashCode) {
        selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, identityHashCode));
        selector = (ConsistentHashSelector<T>) selectors.get(key);
    }
    // 選擇器選擇一個invoker
    return selector.select(invocation);
}

該方法也作了一些invokers 列表是否是變更過,以及建立 ConsistentHashSelector等工做,而後調用selector.select來進行選擇。

2.ConsistentHashSelector
private static final class ConsistentHashSelector<T> {

    /**
     * 存儲 Invoker 虛擬節點
     */
    private final TreeMap<Long, Invoker<T>> virtualInvokers;

    /**
     * 每一個Invoker 對應的虛擬節點數
     */
    private final int replicaNumber;

    /**
     * 原始哈希值
     */
    private final int identityHashCode;

    /**
     * 取值參數位置數組
     */
    private final int[] argumentIndex;

    ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
        this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
        this.identityHashCode = identityHashCode;
        URL url = invokers.get(0).getUrl();
        // 獲取虛擬節點數,默認爲160
        this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes", 160);
        // 獲取參與 hash 計算的參數下標值,默認對第一個參數進行 hash 運算
        String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments", "0"));
        // 建立下標數組
        argumentIndex = new int[index.length];
        // 遍歷
        for (int i = 0; i < index.length; i++) {
            // 記錄下標
            argumentIndex[i] = Integer.parseInt(index[i]);
        }
        // 遍歷invokers
        for (Invoker<T> invoker : invokers) {
            String address = invoker.getUrl().getAddress();
            for (int i = 0; i < replicaNumber / 4; i++) {
                // 對 address + i 進行 md5 運算,獲得一個長度爲16的字節數組
                byte[] digest = md5(address + i);
                // // 對 digest 部分字節進行4次 hash 運算,獲得四個不一樣的 long 型正整數
                for (int h = 0; h < 4; h++) {
                    // h = 0 時,取 digest 中下標爲 0 ~ 3 的4個字節進行位運算
                    // h = 1 時,取 digest 中下標爲 4 ~ 7 的4個字節進行位運算
                    // h = 2, h = 3 時過程同上
                    long m = hash(digest, h);
                    // 將 hash 到 invoker 的映射關係存儲到 virtualInvokers 中,
                    // virtualInvokers 須要提供高效的查詢操做,所以選用 TreeMap 做爲存儲結構
                    virtualInvokers.put(m, invoker);
                }
            }
        }
    }

    /**
     * 選擇一個invoker
     * @param invocation
     * @return
     */
    public Invoker<T> select(Invocation invocation) {
        // 將參數轉爲 key
        String key = toKey(invocation.getArguments());
        // 對參數 key 進行 md5 運算
        byte[] digest = md5(key);
        // 取 digest 數組的前四個字節進行 hash 運算,再將 hash 值傳給 selectForKey 方法,
        // 尋找合適的 Invoker
        return selectForKey(hash(digest, 0));
    }

    /**
     * 將參數轉爲 key
     * @param args
     * @return
     */
    private String toKey(Object[] args) {
        StringBuilder buf = new StringBuilder();
        // 遍歷參數下標
        for (int i : argumentIndex) {
            if (i >= 0 && i < args.length) {
                // 拼接參數,生成key
                buf.append(args[i]);
            }
        }
        return buf.toString();
    }

    /**
     * 經過hash選擇invoker
     * @param hash
     * @return
     */
    private Invoker<T> selectForKey(long hash) {
        // 到 TreeMap 中查找第一個節點值大於或等於當前 hash 的 Invoker
        Map.Entry<Long, Invoker<T>> entry = virtualInvokers.tailMap(hash, true).firstEntry();
        // 若是 hash 大於 Invoker 在圓環上最大的位置,此時 entry = null,
        // 須要將 TreeMap 的頭節點賦值給 entry
        if (entry == null) {
            entry = virtualInvokers.firstEntry();
        }
        // 返回選擇的invoker
        return entry.getValue();
    }

    /**
     * 計算hash值
     * @param digest
     * @param number
     * @return
     */
    private long hash(byte[] digest, int number) {
        return (((long) (digest[3 + number * 4] & 0xFF) << 24)
                | ((long) (digest[2 + number * 4] & 0xFF) << 16)
                | ((long) (digest[1 + number * 4] & 0xFF) << 8)
                | (digest[number * 4] & 0xFF))
                & 0xFFFFFFFFL;
    }

    /**
     * md5
     * @param value
     * @return
     */
    private byte[] md5(String value) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
        md5.reset();
        byte[] bytes;
        try {
            bytes = value.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
        md5.update(bytes);
        return md5.digest();
    }

}

該類是內部類,是一致性 hash 選擇器,首先看它的屬性,利用TreeMap來存儲 Invoker 虛擬節點,由於須要提供高效的查詢操做。再看看它的構造方法,執行了一系列的初始化邏輯,好比從配置中獲取虛擬節點數以及參與 hash 計算的參數下標,默認狀況下只使用第一個參數進行 hash,而且ConsistentHashLoadBalance 的負載均衡邏輯只受參數值影響,具備相同參數值的請求將會被分配給同一個服務提供者。還有一個select方法,比較簡單,先進行md5運算。而後hash,最後選擇出對應的invoker。

(五)RoundRobinLoadBalance

該類是負載均衡基於加權輪詢算法的實現。那麼什麼是加權輪詢,輪詢很好理解,好比我第一個請求分配給A服務器,第二個請求分配給B服務器,第三個請求分配給C服務器,第四個請求又分配給A服務器,這就是輪詢,可是這隻適合每臺服務器性能相近的狀況,這種是一種很是理想的狀況,那更多的是每臺服務器的性能都會有所差別,這個時候性能差的服務器被分到等額的請求,就會須要承受壓力大宕機的狀況,這個時候咱們須要對輪詢加權,我舉個例子,服務器 A、B、C 權重比爲 6:3:1,那麼在10次請求中,服務器 A 將收到其中的6次請求,服務器 B 會收到其中的3次請求,服務器 C 則收到其中的1次請求,也就是說每臺服務器可以收到的請求歸結於它的權重。

1.屬性
/**
 * 回收間隔
 */
private static int RECYCLE_PERIOD = 60000;
2.WeightedRoundRobin
protected static class WeightedRoundRobin {
    /**
     * 權重
     */
    private int weight;
    /**
     * 當前已經有多少請求落在該服務提供者身上,也能夠當作是一個動態的權重
     */
    private AtomicLong current = new AtomicLong(0);
    /**
     * 最後一次更新時間
     */
    private long lastUpdate;
    public int getWeight() {
        return weight;
    }
    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);
    }
    public long getLastUpdate() {
        return lastUpdate;
    }
    public void setLastUpdate(long lastUpdate) {
        this.lastUpdate = lastUpdate;
    }
}

該內部類是一個加權輪詢器,它記錄了某一個服務提供者的一些數據,好比權重、好比當前已經有多少請求落在該服務提供者上等。

3.doSelect
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
    // key = 全限定類名 + "." + 方法名,好比 com.xxx.DemoService.sayHello
    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;
    // 最小權重
    long maxCurrent = Long.MIN_VALUE;
    // 得到如今的時間戳
    long now = System.currentTimeMillis();
    // 建立已經選擇的invoker
    Invoker<T> selectedInvoker = null;
    // 建立加權輪詢器
    WeightedRoundRobin selectedWRR = null;

    // 下面這個循環主要作了這樣幾件事情:
    //   1. 遍歷 Invoker 列表,檢測當前 Invoker 是否有
    //      相應的 WeightedRoundRobin,沒有則建立
    //   2. 檢測 Invoker 權重是否發生了變化,若變化了,
    //      則更新 WeightedRoundRobin 的 weight 字段
    //   3. 讓 current 字段加上自身權重,等價於 current += weight
    //   4. 設置 lastUpdate 字段,即 lastUpdate = now
    //   5. 尋找具備最大 current 的 Invoker,以及 Invoker 對應的 WeightedRoundRobin,
    //      暫存起來,留做後用
    //   6. 計算權重總和
    for (Invoker<T> invoker : invokers) {
        // 得到identify的值
        String identifyString = invoker.getUrl().toIdentityString();
        // 得到加權輪詢器
        WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
        // 計算權重
        int weight = getWeight(invoker, invocation);
        // 若是權重小於0,則設置0
        if (weight < 0) {
            weight = 0;
        }
        // 若是加權輪詢器爲空
        if (weightedRoundRobin == null) {
            // 建立加權輪詢器
            weightedRoundRobin = new WeightedRoundRobin();
            // 設置權重
            weightedRoundRobin.setWeight(weight);
            // 加入集合
            map.putIfAbsent(identifyString, weightedRoundRobin);
            weightedRoundRobin = map.get(identifyString);
        }
        // 若是權重跟以前的權重不同,則從新設置權重
        if (weight != weightedRoundRobin.getWeight()) {
            //weight changed
            weightedRoundRobin.setWeight(weight);
        }
        // 計數器加1
        long cur = weightedRoundRobin.increaseCurrent();
        // 更新最後一次更新時間
        weightedRoundRobin.setLastUpdate(now);
        // 當落在該服務提供者的統計數大於最大可承受的數
        if (cur > maxCurrent) {
            // 賦值
            maxCurrent = cur;
            // 被選擇的selectedInvoker賦值
            selectedInvoker = invoker;
            // 被選擇的加權輪詢器賦值
            selectedWRR = weightedRoundRobin;
        }
        // 累加
        totalWeight += weight;
    }
    // 若是更新鎖不能得到而且invokers的大小跟map大小不匹配
    // 對 <identifyString, WeightedRoundRobin> 進行檢查,過濾掉長時間未被更新的節點。
    // 該節點可能掛了,invokers 中不包含該節點,因此該節點的 lastUpdate 長時間沒法被更新。
    // 若未更新時長超過閾值後,就會被移除掉,默認閾值爲60秒。
    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);
            }
        }
    }
    // 若是被選擇的selectedInvoker不爲空
    if (selectedInvoker != null) {
        // 設置總的權重
        selectedWRR.sel(totalWeight);
        return selectedInvoker;
    }
    // should not happen here
    return invokers.get(0);
}

該方法是選擇的核心,其實關鍵是一些數據記錄,在每次請求都會記錄落在該服務上的請求數,而後在根據權重來分配,而且會有回收時間來處理一些長時間未被更新的節點。

後記

該部分相關的源碼解析地址: https://github.com/CrazyHZM/i...

該文章講解了集羣中關於負載均衡實現的部分,每一個算法都是如今很廣泛的負載均衡算法,但願你們細細品味。接下來我將開始對集羣模塊關於分組聚合部分進行講解。

相關文章
相關標籤/搜索