負載均衡-一致性Hash算法

1. Hash算法

哈希(Hash)也稱爲散列,把任意長度的輸入,通過散列算法變換成固定長度的輸出,該輸出就是散列值、哈希值(hashCode)。(來自:百度百科)

在現實中,設計者常常將散列值作爲索引,用於快速定位數據的位置,比如 HashMap

// cache => key:userId, value:phone
Map<String, String> cache = new HashMap<>();
cache.put("user:001","159xxxx0001");
cache.put("user:002","159xxxx0002");
cache.put("user:003","159xxxx0003");

// 查詢 "user:001" 的手機號
String phone = cache.get("user:001");

爲了引入一致性Hash算法,我需要舉個例子:


現在 A公司 發展良好,上億的用戶量,架構師設計出一個方案:根據用戶id分庫,通過對用戶id進行Hash運算,計算出一個散列值,來決定用戶數據存儲在哪一個節點。

由此出現一個問題,怎麼才能保證數據均勻分佈在各個節點?假如全部數據都存儲在 節點1 這個分庫就是失敗的,和不分庫一模一樣不是嗎?這種狀況專業術語叫數據傾斜。


那怎麼才能均勻存儲在各個節點呢?答案是 1.選擇合適的數據作爲key2.設計優秀的散列函數


跑題了,今天要講的是負載均衡。

下文舉例中,hash算法選最簡單的取餘法,方便理解


如圖所示、顯然、易得,上圖中,有四個請求,有三個節點,我們該怎麼讓請求均勻的打在節點上?這是不是和上面根據用戶ID分庫的栗子有共同之處,首先需要選擇一個合適的數據當作key,還有一個優秀的散列函數,但是這很難很好的實現。

問題1:如何讓請求均勻命中節點?

如果我現在加一個節點,user:004將會映射在 節點0上(注:4%4=0),由於user:004以前將數據存儲在節點1,那麼將查詢不到 user:004的數據。

問題2:如何解決動態增加、減少節點帶來的問題?


2. 一致性Hash算法

背景之類的東西就跳過了。

上面的散列函數是用戶id%節點數,節點數是會動態增減的,那我們把節點數設置爲一個固定的大數(2^32),這樣就解決了動態增加、減少節點帶來的問題。

再上圖:

解釋一下,就是將散列函數變爲 用戶id % \(2^{32}\),如果散列值落在 節點0節點1 之間,那麼我們選擇 節點1 ,同理,如果落在 節點1節點2 之間,我們選擇 節點2 ,我們也稱這個環爲Hash環。


服務器減少:

節點1 掛掉後,其餘節點依舊能正常工作,只不過原本打在 節點1 的請求,按照邏輯,打在了 節點2 上,所以需要將 節點1 的數據全部分配在節點2,這可能造成 節點2 短時間接收大量請求,節點2 也掛掉,然後導致請求全部打在 節點0,從而形成雪崩效應,全部節點掛掉。

服務器增加:

增加 節點4 , 只需將原本在 節點2 的部分數據重新分配在 節點4


上面解決了,增加節點與減少節點,節點數據的問題,但是沒解決一個問題就是,數據傾斜的問題。

如這圖,存儲在 節點2 的數據概率遠多於 節點0,根據概率論,極大可能會造成數據傾斜問題。


解決這個辦法的問題是:添加虛擬節點。

發光的節點爲真實節點,不發光節點爲虛擬節點,這樣一操作,眼睛看着都均勻了,當然虛擬節點越多越均勻(概率論問題),假如請求命中虛擬節點,會將請求轉發至真實節點,不理解了吧。

// 返回一個鍵大於等於給定鍵的最小鍵值對的Entry對象。如果沒有這樣的鍵值對存在,則返回null。
Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);

看個源碼吧:

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.dubbo.rpc.cluster.loadbalance;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.io.Bytes;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.support.RpcUtils;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import static org.apache.dubbo.common.constants.CommonConstants.$INVOKE;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;

/**
 * ConsistentHashLoadBalance
 */
public class ConsistentHashLoadBalance extends AbstractLoadBalance {
    public static final String NAME = "consistenthash";

    /**
     * Hash nodes name
     */
    public static final String HASH_NODES = "hash.nodes";

    /**
     * Hash arguments name
     */
    public static final String HASH_ARGUMENTS = "hash.arguments";

    private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();

    @SuppressWarnings("unchecked")
    @Override
    protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
        // dubbo 把節點包裝成Invoker,invokers 就相當於節點列表
        String methodName = RpcUtils.getMethodName(invocation);
        // eg. com.example.service.getUser 每個方法,對應一個selector
        String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
        // invokers.hashCode() 也就說是節點列表的HashCode
        int invokersHashCode = invokers.hashCode();
        ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
        // 如果selector==null,說明還未初始化,如果selector.identityHashCode != invokersHashCode,說明增加或者減少了節點。
        if (selector == null || selector.identityHashCode != invokersHashCode) {
            selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, invokersHashCode));
            selector = (ConsistentHashSelector<T>) selectors.get(key);
        }
        return selector.select(invocation);
    }

    private static final class ConsistentHashSelector<T> {

        private final TreeMap<Long, Invoker<T>> virtualInvokers;

        private final int replicaNumber;

        private final int identityHashCode;

        private final int[] argumentIndex;

        ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
            // 虛擬節點Map
            this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
            // ConsistentHashSelector 的唯一標識,假如增加、減少節點,那麼唯一標識會發生改變
            this.identityHashCode = identityHashCode;
            URL url = invokers.get(0).getUrl();
            // 虛擬節點數,默認160
            this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160);
            String[] index = 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]);
            }
            // 將虛擬節點放進virtualInvokers
            for (Invoker<T> invoker : invokers) {
                String address = invoker.getUrl().getAddress();
                // 倆個循環,總共 replicaNumber 個虛擬節點,這樣做爲了讓虛擬節點分佈更均勻
                for (int i = 0; i < replicaNumber / 4; i++) {
                    byte[] digest = Bytes.getMD5(address + i);
                    for (int h = 0; h < 4; h++) {
                        long m = hash(digest, h);
                        virtualInvokers.put(m, invoker);
                    }
                }
            }
        }

        public Invoker<T> select(Invocation invocation) {
            boolean isGeneric = invocation.getMethodName().equals($INVOKE);
            String key = toKey(invocation.getArguments(),isGeneric);

            byte[] digest = Bytes.getMD5(key);
            return selectForKey(hash(digest, 0));
        }

        private String toKey(Object[] args, boolean isGeneric) {
            return isGeneric ? toKey((Object[]) args[1]) : toKey(args);
        }

        private String toKey(Object[] args) {
            StringBuilder buf = new StringBuilder();
            for (int i : argumentIndex) {
                if (i >= 0 && args != null && i < args.length) {
                    buf.append(args[i]);
                }
            }
            return buf.toString();
        }

        private Invoker<T> selectForKey(long hash) {
            // 返回一個鍵大於等於給定鍵的最小鍵值對的Entry對象。如果沒有這樣的鍵值對存在,則返回null。
            Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
            if (entry == null) {
                entry = virtualInvokers.firstEntry();
            }
            return entry.getValue();
        }
        
        // hash環2^32體現在這裏,0xFFFFFFFFL = 2^32 - 1,說明 hash值只能取到0 ~ 2^32-1
        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;
        }
    }

}


3. 總結

Hash算法: 用戶id % 節點數,常被當作索引,用來快速定位數據,但是在負載均衡這個問題上,存在容易導致數據傾斜動態增減節點的問題。

一致性Hash算法,通過將Hash環分爲2^32個插槽,巧妙利用虛擬節點,提供瞭解決數據傾斜動態增減節點的思路。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章