1. 程式人生 > >一致性hash算法實現(偽碼)

一致性hash算法實現(偽碼)

得到 nod 表頭 www 用戶 value .cn dex 介紹

一致性Hash算法原理參考此博客,介紹的比較詳細:https://www.cnblogs.com/lpfuture/p/5796398.html

預設場景:所有請求過來,會根據一致性hash算法,選擇一個服務器轉發出去,一致性hash算法獲取到的是服務器的ip。

假定節點存儲結構如下:

class Node{
    String addr; //存放服務器的ip
}

實現方案一(bitmap+HashMap)

借助數據結構

1. 2^32長度的bitmap,用於標記有節點的下表

2. HashMap,用於存儲下標到對象的映射

數據查找偽碼實現如下:

bitmap = [0,0,0,1,0,0,1,...0]; //
2^32的bitmap,每個為1的值標識此位置包含node indexToAddr<Integer, Node> map; //存儲bitmap中獲取的位置下標到Node的映射 n=hash(x); //x假設為請求中獲取到的用戶id,通過hash算法可以得到一個0-2^32-1之間的整數 //開始計算 while(bitmap[n] != 1){ n = (n+1)%2^32; } //n即為node在環中占的位置,從hash中取出此值 Node node = map.get(n); return node.addr;

節點插入偽碼實現如下:

Node toBeInsert = new
Node(x); //插入值為x的節點 int n = hash(x); bitmap[n] = 1; //置位為1 map.put(n, toBeInsert);

這種方式完全是按照原理中介紹的來實現的,需要用到一個2^32的bitmap,如果不進行壓縮,需要占用512M的空間。占用空間較大,但是能直接定位到值。

實現方案二(鏈表)

借助數據結構:鏈表

class LinkNode{     //定義鏈表數據結構
    LinkNode next;
    int index; //下標
    Node value;
}

LinkNode head = []->[]->...->[]->head; //
按照index排序的鏈表 int n=hash(x); LinkNode front = null; LinkNode cur=head; while(cur.index<n){ front = cur; cur = cur.next; } if(front == null) front = head; return front.val.node;

鏈表的方式每次都會從表頭開始遍歷一遍才能找到指定位置

鏈表方式的插入:直接創建一個節點插入進來就可以了,保證鏈表是有序的。

一致性hash算法實現(偽碼)