西西軟件園多重安全檢測下載網(wǎng)站、值得信賴的軟件下載站!
軟件
軟件
文章
搜索

首頁編程開發(fā)C#.NET → 用c#實現(xiàn)一致性Hash算法(KetamaHash)

用c#實現(xiàn)一致性Hash算法(KetamaHash)

相關軟件相關文章發(fā)表評論 來源:本站整理時間:2010/8/24 18:04:18字體大。A-A+

作者:佚名點擊:612次評論:0次標簽: Hash

abylon FREEHASH1.5 安裝版
  • 類型:密碼相關大小:9.4M語言:英文 評分:5.0
  • 標簽:
立即下載

 最近在研究"一致性HASH算法"(Consistent Hashing),用于解決memcached集群中當服務器出現(xiàn)增減變動時對散列值的影響。后來 在JAVAEYE上的一篇文章中,找到了其中的 KetamaHash 算法的JAVA實現(xiàn)(一種基于虛擬結點的HASH算法),于是為了加深理解,對照 JAVA版本,用C#重寫了一個。放到這里,如果大家感興趣的話, 可以下載測試一下,如果發(fā)現(xiàn)寫法有問題請及時告之我,以便我及時修正。
 
      下面是對Ketama的介紹:
 Ketama is an implementation of a consistent hashing algorithm, meaning you can add or remove servers from the memcached pool without causing a complete remap of all keys.
 Here’s how it works:
 * Take your list of servers (eg: 1.2.3.4:11211, 5.6.7.8:11211, 9.8.7.6:11211)
 * Hash each server string to several (100-200) unsigned ints
 * Conceptually, these numbers are placed on a circle called the continuum. (imagine a clock face that goes from 0 to 2^32)
 * Each number links to the server it was hashed from, so servers appear at several points on the continuum, by each of the numbers they hashed to.
 * To map a key->server, hash your key to a single unsigned int, and find the next biggest number on the continuum. The server linked to that number is the correct server for that key.
 * If you hash your key to a value near 2^32 and there are no points on the continuum greater than your hash, return the first server in the continuum.
 If you then add or remove a server from the list, only a small proportion of keys end up mapping to different servers.
 

           我的理解,這類方法其實有點像大學里的微積分的思想(通過連續(xù)函數(shù)的取值區(qū)間來計算圖形面積)。通過把已知的實結點(memcached服務IP端口)列表結成一個圓,然后在兩兩實結點之間“放置”盡可能多的虛擬節(jié)點(上面文中的unsigned ints), 假設用戶數(shù)據(jù)映射在虛擬節(jié)點上(用戶數(shù)據(jù)真正存儲位置是在該虛擬節(jié)點代表的實際物理服務器上),這樣就能抑制分布不均勻,最大限度地減小服務器增減時的緩存重新分布。如下圖:

   

             下面是添加結點時:


    
                  
         如這篇文章所說(總結一致性哈希(Consistent Hashing) ):
   
      Consistent Hashing最大限度地抑制了hash鍵的重新分布。另外要取得比較好的負載均衡的效果,往往在服務器數(shù)量比較少的時候需要增加虛擬節(jié)點來保證服務器能均勻的分布在圓環(huán)上。因為使用一般的hash方法,服務器的映射地點的分布非常不均勻。使用虛擬節(jié)點的思想,為每個物理節(jié)點(服務器)在圓上分配100~200個點。這樣就能抑制分布不均勻,最大限度地減小服務器增減時的緩存重新分布。用戶數(shù)據(jù)映射在虛擬節(jié)點上,就表示用戶數(shù)據(jù)真正存儲位置是在該虛擬節(jié)點代表的實際物理服務器上。

       了解了原理,下面看一下具體實現(xiàn)。

       JAVA實現(xiàn)代碼取自Spy Memcached client中的類,原文的作者也盡可能的對代碼進行注釋說明,所以讓我剩了不少時間。
   
      

    相關評論

    閱讀本文后您有什么感想? 已有人給出評價!

    • 8 喜歡喜歡
    • 3 頂
    • 1 難過難過
    • 5 囧
    • 3 圍觀圍觀
    • 2 無聊無聊

    熱門評論

    最新評論

    發(fā)表評論 查看所有評論(0)

    昵稱:
    表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
    字數(shù): 0/500 (您的評論需要經(jīng)過審核才能顯示)