簡陋版一致性hash演算法實現

來源:互聯網
上載者:User

標籤:一致性hash   value   blog   hub   git   div   cti   public   儲存   

 1     public function hashAction(){ 2             $server_list = range(14,114); 3             $server_slot = $this->hashAri($server_list); 4             $key_list = range(1,100000); 5             $key_slot = $this->hashAri($key_list); 6            7             //分配位子 8             $result = $this->hashSlot($server_slot,$key_slot); 9             $count = count($key_list);10             foreach ($result as $key=>$val){11                 echo "slot = ".$key." rate=".count($val)/$count."<br>";12             }13         }14         15         public function hashSlot($server_slot,$key_slot){16             $result = array();17             $min = 0;18             foreach ($server_slot as $key=>$value){19                 $max = $key;20                 foreach ($key_slot as $k=>$v){21                     if($k>$min && $k<$max)$result[$value][] = $v;22                 }23                 $min = $key;24             }25             return $result;26         }27         28         public function hashAri($list){29             $result = array();30             foreach ($list as $key){31                 $slot = rand(1,pow(2,30));32                 $result[$slot] = $key;33             }34             ksort($result);35             return $result;36         }

 相關部落格:http://blog.csdn.net/cywosp/article/details/23397179#quote繼續的部落格:http://yikun.github.io/2016/06/09/%E4%B8%80%E8%87%B4%E6%80%A7%E5%93%88%E5%B8%8C%E7%AE%97%E6%B3%95%E7%9A%84%E7%90%86%E8%A7%A3%E4%B8%8E%E5%AE%9E%E8%B7%B5/  解決問題:

  一般取餘數的hash演算法,新增或者刪除機器,幾乎所有的key都需要重新對應

原理:

將機器和key都按照同一個hash演算法,映射到一個圓環上,所有的key順時針,尋找離他最近的機器,找到並儲存到該機器上

為瞭解決分布不均問題:

虛擬機器id

    就是把實體機器,複製出幾個虛擬id,映射到圓環上,一定程度可以負載平衡

圖例:

正常的一致性hash映射

刪掉一個機器的映射

添加虛擬id之後的映射

    

簡陋版一致性hash演算法實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.