溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

一致性哈希算法的java實現(xiàn)是怎樣的

發(fā)布時間:2021-11-24 16:10:35 來源:億速云 閱讀:152 作者:柒染 欄目:云計算

這篇文章給大家介紹一致性哈希算法的java實現(xiàn)是怎樣的,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

今天我們用java來實現(xiàn)一下,一致性哈希算法,重點還是一致性和虛擬節(jié)點2個方面。

廢話少說,直接上代碼:

public class ConsistencyHash {
    private TreeMap<Long, String> nodes = null;
    
    private List<String> shards = new ArrayList<String>();
    
    private int VIRTUAL_NUM = 4;

    
    public void init() {
        shards.add("10.10.0.0-服務(wù)器0");
        shards.add("10.10.0.1-服務(wù)器1");
        shards.add("10.10.0.2-服務(wù)器2");
        shards.add("10.10.0.3-服務(wù)器3");
        shards.add("10.10.0.4-服務(wù)器4");

        nodes = new TreeMap<Long, String>();
        for (int i = 0; i < shards.size(); i++) {
            String shardInfo = shards.get(i);
            for (int j = 0; j < VIRTUAL_NUM; j++) {
                byte[] md5Value = computeMd5("SHARD-" + i + "-NODE-" + j);
                long hashCode = hash(md5Value, j);
                System.out.println(hashCode);
                nodes.put(hashCode, shardInfo);
            }
        }
        
        Iterator<Long> iter = nodes.keySet().iterator();
        while(iter.hasNext()){
            Long key = iter.next();
            String obj = (String)nodes.get(key);
            System.out.println(String.valueOf(key) + ":" + obj);
        }
    }

    
    public Object getShardInfo(long hash) {
        Long key = hash;
        SortedMap<Long, String> tailMap = nodes.tailMap(key);
        if (tailMap.isEmpty()) {
            key = nodes.firstKey();
        } else {
            key = tailMap.firstKey();
        }
        return nodes.get(key);
    }

    
    public void printMap() {
        System.out.println(nodes);
    }

    
    public long hash(byte[] digest, int nTime) {
        long rv = ((long) (digest[3 + nTime * 4] & 0xFF) << 24) | ((long) (digest[2 + nTime * 4] & 0xFF) << 16)
                | ((long) (digest[1 + nTime * 4] & 0xFF) << 8) | (digest[0 + nTime * 4] & 0xFF);

        return rv & 0xffffffffL; /* Truncate to 32-bits */
    }

    /**
     * Get the md5 of the given key. 計算MD5值
     */
    public byte[] computeMd5(String k) {
        MessageDigest md5;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 not supported", e);
        }
        md5.reset();
        byte[] keyBytes = null;
        try {
            keyBytes = k.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Unknown string :" + k, e);
        }

        md5.update(keyBytes);
        byte[] res = md5.digest();
        return res;
    }

    public static void main(String[] args) {
        Random ran = new Random();
        ConsistencyHash hash = new ConsistencyHash();
        hash.init();
        hash.printMap();

        for (int i = 0; i < 256; i++) {
            int randomVirtualServer = ran.nextInt(hash.VIRTUAL_NUM);
            byte[] md5Value = hash.computeMd5(String.valueOf(i));
            long hashValue = hash.hash(md5Value, randomVirtualServer);
            String serverInfo = (String)hash.getShardInfo(hashValue);
            System.out.println(serverInfo);
        }
    }
}

環(huán)境:假定為5臺真實服務(wù)器,每臺真實服務(wù)器對應(yīng)4個虛擬節(jié)點,這樣就是20個服務(wù)節(jié)點。

首先是init()方法,該方法就是把20個服務(wù)節(jié)點,分布在一個2^32的圓環(huán)上。這里分為2步,首先根據(jù)形如“ SHARD-2-NODE-3 ”這樣的字符串得到一個16個長度的byte數(shù)組;之后根據(jù)這個byte數(shù)組獲得2^32范圍內(nèi)的哈希值。

然后假定256個數(shù)據(jù)對象,我們需要為他們分別找到一個服務(wù)節(jié)點。

根據(jù)一致性的定義,我們需要根據(jù)這256個數(shù)據(jù)對象,分別一個 2^32范圍內(nèi)的哈希值 ,為了方便起見,我們采取和服務(wù)節(jié)點一致的方法。

之后,在 getShardInfo 方法當(dāng)中,在圓環(huán)內(nèi),為他們尋找各自所屬的服務(wù)節(jié)點。

關(guān)于一致性哈希算法的java實現(xiàn)是怎樣的就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI