Memcached 一致性hash原理

memcache 是一個分佈式的緩存系統,但是本身沒有提供集羣功能,在大型應用的情況下容易成爲瓶頸。但是客戶端這個時候可以自由擴展,分兩階段實現。第一階段:key 要先根據一定的算法映射到一臺memcache服務器。第二階段從服務器中取出緩存的值。但是有一個問題,比如其中一臺服務器掛了,或者需要增加一臺服務 的時候,這個時候第一階段的算法就很重要了,怎樣使得原來的數據儘可能的繼續有效,減少擴展節點或縮減節點帶來的衝擊。下面列出想到一些解決方法:

一:hash一致性算法:

優點:

當一個節點失效的時候,其他節點的數據不會受到破壞,這個節點的數據會被分流到另外一個節點。當增加一個節點時,只會對一個節點的一分部數據有影響。

缺點:

極容易造成節點間數據量的不平衡,可能一個節點上熱點非常多,一個節點上熱點很少。

下面是具體介紹:(轉自:http://blog.csdn.net/sparkliang/archive/2010/02/02/5279393.aspx

consistent hashing 算法早在 1997 年就在論文 Consistent hashing and random trees中被提出,目前在 cache 系統中應用越來越廣泛;

1 基本場景

比如你有 N 個 cache 服務器(後面簡稱 cache ),那麼如何將一個對象 object 映射到 N 個 cache 上呢,你很可能會採用類似下面的通用方法計算 object 的 hash 值,然後均勻的映射到到 N 個 cache ;

hash(object)%N

一切都運行正常,再考慮如下的兩種情況;

1 一個 cache 服務器 m down 掉了(在實際應用中必須要考慮這種情況),這樣所有映射到 cache m 的對象都會失效,怎麼辦,需要把 cache m 從 cache 中移除,這時候 cache 是 N-1 臺,映射公式變成了 hash(object)%(N-1) ;

2 由於訪問加重,需要添加 cache ,這時候 cache 是 N+1 臺,映射公式變成了 hash(object)%(N+1) ;

1 和 2 意味着什麼?這意味着突然之間幾乎所有的 cache 都失效了。對於服務器而言,這是一場災難,洪水般的訪問都會直接衝向後臺服務器;

再來考慮第三個問題,由於硬件能力越來越強,你可能想讓後面添加的節點多做點活,顯然上面的 hash 算法也做不到。

  有什麼方法可以改變這個狀況呢,這就是 consistent hashing...

2 hash 算法和單調性

         Hash 算法的一個衡量指標是單調性( Monotonicity ),定義如下:

        單調性是指如果已經有一些內容通過哈希分派到了相應的緩衝中,又有新的緩衝加入到系統中。哈希的結果應能夠保證原有已分配的內容可以被映射到新的緩衝中去,而不會被映射到舊的緩衝集合中的其他緩衝區。

容易看到,上面的簡單 hash 算法 hash(object)%N 難以滿足單調性要求。

3 consistent hashing 算法的原理

consistent hashing 是一種 hash 算法,簡單的說,在移除 / 添加一個 cache 時,它能夠儘可能小的改變已存在 key 映射關係,儘可能的滿足單調性的要求。

下面就來按照 5 個步驟簡單講講 consistent hashing 算法的基本原理。

3.1 環形hash 空間

考慮通常的 hash 算法都是將 value 映射到一個 32 爲的 key 值,也即是 0~2^32-1 次方的數值空間;我們可以將這個空間想象成一個首( 0)尾( 2^32-1 )相接的圓環,如下面圖 1 所示的那樣。

memcache 集羣

圖 1 環形 hash 空間

3.2 把對象映射到hash 空間

接下來考慮 4 個對象 object1~object4 ,通過 hash 函數計算出的 hash 值 key 在環上的分佈如圖 2 所示。

hash(object1) = key1;

… …

hash(object4) = key4;

memcache 集羣

圖 2 4 個對象的 key 值分佈

3.3 把cache 映射到hash 空間

Consistent hashing 的基本思想就是將對象和 cache 都映射到同一個 hash 數值空間中,並且使用相同的 hash 算法。

假設當前有 A,B 和 C 共 3 臺 cache ,那麼其映射結果將如圖 3 所示,他們在 hash 空間中,以對應的 hash 值排列。

hash(cache A) = key A;

… …

hash(cache C) = key C;

memcache 集羣

圖 3 cache 和對象的 key 值分佈

說到這裏,順便提一下 cache 的 hash 計算,一般的方法可以使用 cache 機器的 IP 地址或者機器名作爲 hash 輸入。

3.4 把對象映射到cache

現在 cache 和對象都已經通過同一個 hash 算法映射到 hash 數值空間中了,接下來要考慮的就是如何將對象映射到 cache 上面了。

在這個環形空間中,如果沿着順時針方向從對象的 key 值出發,直到遇見一個 cache ,那麼就將該對象存儲在這個 cache 上,因爲對象和 cache 的 hash 值是固定的,因此這個 cache 必然是唯一和確定的。這樣不就找到了對象和 cache 的映射方法了嗎?!

依然繼續上面的例子(參見圖 3 ),那麼根據上面的方法,對象 object1 將被存儲到 cache A 上; object2 和 object3 對應到 cache C ; object4 對應到 cache B ;

3.5 考察cache 的變動

前面講過,通過 hash 然後求餘的方法帶來的最大問題就在於不能滿足單調性,當 cache 有所變動時, cache 會失效,進而對後臺服務器造成巨大的衝擊,現在就來分析分析 consistent hashing 算法。

3.5.1 移除 cache

考慮假設 cache B 掛掉了,根據上面講到的映射方法,這時受影響的將僅是那些沿 cache B 逆時針遍歷直到下一個 cache ( cache C )之間的對象,也即是本來映射到 cache B 上的那些對象。

因此這裏僅需要變動對象 object4 ,將其重新映射到 cache C 上即可;參見圖 4 。

memcache 集羣

圖 4 Cache B 被移除後的 cache 映射

3.5.2 添加 cache

再考慮添加一臺新的 cache D 的情況,假設在這個環形 hash 空間中, cache D 被映射在對象 object2 和 object3 之間。這時受影響的將僅是那些沿 cache D 逆時針遍歷直到下一個 cache ( cache B )之間的對象(它們是也本來映射到 cache C 上對象的一部分),將這些對象重新映射到 cache D 上即可。

因此這裏僅需要變動對象 object2 ,將其重新映射到 cache D 上;參見圖 5 。

memcache 集羣

圖 5 添加 cache D 後的映射關係

4 虛擬節點

考量 Hash 算法的另一個指標是平衡性 (Balance) ,定義如下:

平衡性

        平衡性是指哈希的結果能夠儘可能分佈到所有的緩衝中去,這樣可以使得所有的緩衝空間都得到利用。

hash 算法並不是保證絕對的平衡,如果 cache 較少的話,對象並不能被均勻的映射到 cache 上,比如在上面的例子中,僅部署 cache A 和 cache C 的情況下,在 4 個對象中, cache A 僅存儲了 object1 ,而 cache C 則存儲了 object2 、 object3 和 object4 ;分佈是很不均衡的。

爲了解決這種情況, consistent hashing 引入了“虛擬節點”的概念,它可以如下定義:

“虛擬節點”( virtual node )是實際節點在 hash 空間的複製品( replica ),一實際個節點對應了若干個“虛擬節點”,這個對應個數也成爲“複製個數”,“虛擬節點”在 hash 空間中以 hash 值排列。

仍以僅部署 cache A 和 cache C 的情況爲例,在圖 4 中我們已經看到, cache 分佈並不均勻。現在我們引入虛擬節點,並設置“複製個數”爲 2 ,這就意味着一共會存在 4 個“虛擬節點”, cache A1, cache A2 代表了 cache A ; cache C1, cache C2 代表了 cache C ;假設一種比較理想的情況,參見圖 6 。

memcache 集羣

圖 6 引入“虛擬節點”後的映射關係

此時,對象到“虛擬節點”的映射關係爲:

objec1->cache A2 ; objec2->cache A1 ; objec3->cache C1 ; objec4->cache C2 ;

因此對象 object1 和 object2 都被映射到了 cache A 上,而 object3 和 object4 映射到了 cache C 上;平衡性有了很大提高。

引入“虛擬節點”後,映射關係就從 { 對象 -> 節點 } 轉換到了 { 對象 -> 虛擬節點 } 。查詢物體所在 cache 時的映射關係如圖 7 所示。

memcache 集羣

圖 7 查詢對象所在 cache

“虛擬節點”的 hash 計算可以採用對應節點的 IP 地址加數字後綴的方式。例如假設 cache A 的 IP 地址爲 202.168.14.241 。

引入“虛擬節點”前,計算 cache A 的 hash 值:

Hash(“202.168.14.241”);

引入“虛擬節點”後,計算“虛擬節”點 cache A1 和 cache A2 的 hash 值:

Hash(“202.168.14.241#1”);  // cache A1

Hash(“202.168.14.241#2”);  // cache A2

5 小結

Consistent hashing 的基本原理就是這些,具體的分佈性等理論分析應該是很複雜的,不過一般也用不到。

http://weblogs.java.net/blog/2007/11/27/consistent-hashing 上面有一個 java 版本的例子,可以參考。

http://blog.csdn.net/mayongzhan/archive/2009/06/25/4298834.aspx 轉載了一個 PHP 版的實現代碼。

http://www.codeproject.com/KB/recipes/lib-conhash.aspx C語言版本

一些參考資料地址:

http://portal.acm.org/citation.cfm?id=258660

http://en.wikipedia.org/wiki/Consistent_hashing

http://www.spiteful.com/2008/03/17/programmers-toolbox-part-3-consistent-hashing/

http://weblogs.java.net/blog/2007/11/27/consistent-hashing

http://tech.idv2.com/2008/07/24/memcached-004/

http://blog.csdn.net/mayongzhan/archive/2009/06/25/4298834.aspx

此文章轉載於:

http://www.open-open.com/lib/view/open1340337319596.html

php對一致性hash分佈不均,使用虛擬節點,看了http://bbs.phpchina.com/forum.php?mod=viewthread&tid=233897這個之後,自己對查找算法進行了修改:

  1. <?php  
  2. class memcacheHashMap{ 
  3.     private $_node =array(); 
  4.      
  5.     private $_nodeData =array(); 
  6.      
  7.     private $_keyNode = 0; 
  8.      
  9.     private $_memcache = null; 
  10.      
  11.      
  12.     // 每個物理服務器生成虛擬節點的個數 
  13.     private $_virtualNodeNum = 200; 
  14.      
  15.     private function __construct(){ 
  16.         // 配置文件 
  17.         $config = array
  18.             "127.0.0.1:11211"
  19.             "127.0.0.1:11212"
  20.             "127.0.0.1:11213"
  21.             "127.0.0.1:11214"
  22.             "127.0.0.1:11215" 
  23.         ); 
  24.          
  25.         if (!$config){ 
  26.             throw new Exception("cache config null"); 
  27.         } 
  28.          
  29.         // 設置虛擬節點 
  30.         foreach($configas $key=>$value){ 
  31.              
  32.             for ($i = 0;$i < $this->_virtualNodeNum;$i++){ 
  33.                 $this->_node[sprintf("%u", crc32($value."#".$i))] = $value."#".$i
  34.             } 
  35.         } 
  36.          
  37.         // 排序 
  38.         ksort($this->_node); 
  39.          
  40. //      print_r($this->_node); 
  41.     } 
  42.      
  43.     // 單例模式 
  44.     static publicfunction getInstance(){ 
  45.         static $memcacheObj = null; 
  46.         if (!is_object($memcacheObj)) { 
  47.             $memcacheObj = new self(); 
  48.         } 
  49.         return $memcacheObj
  50.     } 
  51.      
  52.     private function _connectMemcache($key){ 
  53.         $this->_nodeData = array_keys($this->_node); 
  54. //      echo "all node:\n"; 
  55. //      print_r($this->_nodeData); 
  56.         $this->_keyNode = sprintf("%u", crc32($key)); 
  57. //      $this->_keyNode = 1803717635; 
  58. //      var_dump($this->_keyNode); 
  59.          
  60.         // 獲取key值對應的最近的節點 
  61.         $nodeKey = $this->_findServerNode(0,count($this->_nodeData)-1); 
  62. //      var_dump($nodeKey); 
  63. //      echo "$this->_keyNode :search node:$nodeKey  IP:{$this->_node[$nodeKey]}\n"; 
  64.          
  65.         //獲取對應的真實ip 
  66.         list($config, $num) =explode("#",$this->_node[$nodeKey]); 
  67.          
  68.         if (empty($config)){ 
  69.             throw new Exception("serach ip config error"); 
  70.         } 
  71.          
  72.         if (!isset($this->_memcache[$config])){ 
  73.             $this->_memcache[$config] =new Memcache; 
  74.             list($host, $port) =explode(":",$config); 
  75.             $this->_memcache[$config]->connect($host,$port); 
  76.         } 
  77.          
  78.         return $this->_memcache[$config]; 
  79.          
  80.          
  81.          
  82.     } 
  83.     /**
  84.      * 採用二分法從虛擬memcache節點中查找最近的節點
  85.      * @param int $low 開始位置
  86.      * @param int $high 結束位置
  87.      *
  88.      */ 
  89.     private function _findServerNode($low,$high){ 
  90.          
  91.         // 開始下標小於結束下標 
  92.         if ($low <$high){ 
  93.              
  94.             $avg = intval(($low+$high)/2); 
  95.              
  96.             if ($this->_nodeData[$avg] ==$this->_keyNode){ 
  97.                 return $this->_nodeData[$avg]; 
  98.             }elseif ($this->_keyNode <$this->_nodeData[$avg]){ 
  99.                 return $this->_findServerNode($low,$avg-1); 
  100.             }else
  101.                 return $this->_findServerNode($avg+1,$high); 
  102.             } 
  103.         }else if(($low ==$high)){ 
  104.             // 大於平均值 
  105.             if ($low ==0 ||$low == count($this->_nodeData)-1){ 
  106.                 return $this->_nodeData[$low]; 
  107.             } 
  108. //          var_dump($low); 
  109.             if ($this->_nodeData[$low] <$this->_keyNode){ 
  110.                  
  111.                 if (abs($this->_nodeData[$low] -$this->_keyNode) < abs($this->_nodeData[$low+1]-$this->_keyNode)){ 
  112.                     return $this->_nodeData[$low]; 
  113.                 }else
  114.                     return $this->_nodeData[$low+1]; 
  115.                 } 
  116.          
  117.             }else
  118.                 if (abs($this->_nodeData[$low] -$this->_keyNode) < abs($this->_nodeData[$low-1]-$this->_keyNode)){ 
  119.                     return$this->_nodeData[$low]; 
  120.                 }else
  121.                     return$this->_nodeData[$low-1]; 
  122.                 } 
  123.             } 
  124.         }else
  125.             if ( ($low == 0)&&($high < 0) ){ 
  126.                 return $this->_nodeData[$low]; 
  127.             } 
  128.          
  129.             if (abs($this->_nodeData[$low] -$this->_keyNode) < abs($this->_nodeData[$high]-$this->_keyNode)){ 
  130.                 return $this->_nodeData[$low]; 
  131.             }else
  132.                 return $this->_nodeData[$high]; 
  133.             } 
  134.         } 
  135.     } 
  136.      
  137.     public function set($key,$value, $expire=0){ 
  138. //  var_dump($key); 
  139.         return $this->_connectMemcache($key)->set($key, json_encode($value), 0, $expire); 
  140.     } 
  141.      
  142.      
  143.     public function add($key,$vakue, $expire=0){ 
  144.         return $this->_connectMemcache($key)->add($key, json_encode($value), 0, $expire); 
  145.     } 
  146.      
  147.     public function get($key){ 
  148.         return $this->_connectMemcache($key)->get($key, true); 
  149.     } 
  150.      
  151.     public functiondelete($key){ 
  152.         return $this->_connectMemcache($key)->delete($key); 
  153.     } 
  154.      
  155.          
  156.      
  157.  
  158.  
  159. $runData['BEGIN_TIME'] = microtime(true); 
  160. //測試一萬次set加get 
  161. for($i=0;$i<10000;$i++) { 
  162.         $key = md5(mt_rand()); 
  163. //        var_dump($key); 
  164.         $b = memcacheHashMap::getInstance()->set($key, time(), 10); 
  165. echo "一致性hash:"
  166. var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6)); 
  167. $runData['BEGIN_TIME'] = microtime(true);  
  168. $m= new Memcache; 
  169. $m->connect('127.0.0.1', 11211);  
  170. for($i=0;$i<10000;$i++) { 
  171.         $key = md5(mt_rand()); 
  172.         $b = $m->set($key, time(), 0, 10); 
  173. echo "單臺機器:"
  174. var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6)); 

測試結果:

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