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這個之後,自己對查找算法進行了修改:

<?php 
class memcacheHashMap{
	private $_node = array();
	
	private $_nodeData = array();
	
	private $_keyNode = 0;
	
	private $_memcache = null;
	
	
	// 每個物理服務器生成虛擬節點的個數
	private $_virtualNodeNum = 200;
	
	private function __construct(){
		// 配置文件
		$config = array(
			"127.0.0.1:11211",
			"127.0.0.1:11212",
			"127.0.0.1:11213",
			"127.0.0.1:11214",
			"127.0.0.1:11215"
		);
		
		if (!$config){
			throw new Exception("cache config null");
		}
		
		// 設置虛擬節點
		foreach($config as $key=>$value){
			
			for ($i = 0; $i < $this->_virtualNodeNum; $i++){
				$this->_node[sprintf("%u", crc32($value."#".$i))] = $value."#".$i;
 			}
		}
		
		// 排序
		ksort($this->_node);
		
//		print_r($this->_node);
	}
	
	// 單例模式
	static public function getInstance(){
		static $memcacheObj = null;
		if (!is_object($memcacheObj)) {
			$memcacheObj = new self();
		}
		return $memcacheObj;
	}
	
	private function _connectMemcache($key){
		$this->_nodeData = array_keys($this->_node);
//		echo "all node:\n";
//		print_r($this->_nodeData);
		$this->_keyNode = sprintf("%u", crc32($key));
//		$this->_keyNode = 1803717635;
//		var_dump($this->_keyNode);
		
		// 獲取key值對應的最近的節點
		$nodeKey = $this->_findServerNode(0, count($this->_nodeData)-1);
//		var_dump($nodeKey);
//		echo "$this->_keyNode :search node:$nodeKey  IP:{$this->_node[$nodeKey]}\n";
		
		//獲取對應的真實ip
		list($config, $num) = explode("#", $this->_node[$nodeKey]);
		
		if (empty($config)){
			throw new Exception("serach ip config error");
		}
		
		if (!isset($this->_memcache[$config])){
			$this->_memcache[$config] = new Memcache;
			list($host, $port) = explode(":", $config);
			$this->_memcache[$config]->connect($host, $port);
		}
		
		return $this->_memcache[$config];
		
		
		
	}
	/**
	 * 採用二分法從虛擬memcache節點中查找最近的節點
	 * @param int $low 開始位置
	 * @param int $high 結束位置
	 * 
	 */
	private function _findServerNode($low, $high){
		
		// 開始下標小於結束下標
		if ($low < $high){
			
			$avg = intval(($low+$high)/2);
			
			if ($this->_nodeData[$avg] == $this->_keyNode){
				return $this->_nodeData[$avg];
			}elseif ($this->_keyNode < $this->_nodeData[$avg]){
				return $this->_findServerNode($low, $avg-1);
			}else{
				return $this->_findServerNode($avg+1, $high);
			}
		}else if(($low == $high)){
			// 大於平均值
			if ($low ==0 || $low == count($this->_nodeData)-1){
				return $this->_nodeData[$low];
			}
//			var_dump($low);
			if ($this->_nodeData[$low] < $this->_keyNode){
				
				if (abs($this->_nodeData[$low] - $this->_keyNode) < abs($this->_nodeData[$low+1]-$this->_keyNode)){
					return $this->_nodeData[$low];
				}else{
					return $this->_nodeData[$low+1];
				}
		
			}else {
				if (abs($this->_nodeData[$low] - $this->_keyNode) < abs($this->_nodeData[$low-1]-$this->_keyNode)){
					return $this->_nodeData[$low];
				}else{
					return $this->_nodeData[$low-1];
				}
			}
		}else{
			if ( ($low == 0)&&($high < 0) ){
				return $this->_nodeData[$low];
			}
		
			if (abs($this->_nodeData[$low] - $this->_keyNode) < abs($this->_nodeData[$high]-$this->_keyNode)){
				return $this->_nodeData[$low];
			}else{
				return $this->_nodeData[$high];
			}
		}
	}
	
	public function set($key, $value, $expire=0){
//	var_dump($key);
		return $this->_connectMemcache($key)->set($key, json_encode($value), 0, $expire);
	}
	
	
	public function add($key, $vakue, $expire=0){
		return $this->_connectMemcache($key)->add($key, json_encode($value), 0, $expire);
	}
	
	public function get($key){
		return $this->_connectMemcache($key)->get($key, true);
	}
	
	public function delete($key){
		return $this->_connectMemcache($key)->delete($key);
	}
	
		
	
}


$runData['BEGIN_TIME'] = microtime(true);
//測試一萬次set加get
for($i=0;$i<10000;$i++) {
        $key = md5(mt_rand());
//        var_dump($key);
        $b = memcacheHashMap::getInstance()->set($key, time(), 10);
}
echo "一致性hash:";
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));
$runData['BEGIN_TIME'] = microtime(true); 
$m= new Memcache;
$m->connect('127.0.0.1', 11211); 
for($i=0;$i<10000;$i++) {
        $key = md5(mt_rand());
        $b = $m->set($key, time(), 0, 10);
}
echo "單臺機器:";
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));

測試結果:






根據http://blog.csdn.net/mayongzhan/article/details/4298834進行了修改與測試

下邊查找真實節點的原理是:將虛擬後的節點排序,返回第一個比key哈希後大的節點,若不存在則返回第一個


<?php
/**
 * 一致性hahs實現類
 * 
 */
class FlexiHash{
	/**
	 * var int
	 * 虛擬節點
	 */
	private $_replicas = 200;
	
	/**
	 * 使用hash方法
	 */
	private $_hasher = null;
	
	/**
	 * 真實節點計數器
	 * 
	 */
	private $_tagertCount = 0;
	
	/**
	 * 位置對應節點,用戶lookup中根據位置確定要訪問的節點
	 */
	private $_positionToTarget = array();
	
	/**
	 * 節點對應位置,用於刪除節點
	 */
	private $_targetToPositions = array();
	
	/**
	 * 是否已排序
	 */
	private $_positionToTargetSorted = false;
	
	/**
	 * @ $hasher hash方法
	 * @ $replicas 虛擬節點的個數
	 * 
	 * 確定要使用的hash方法和虛擬的節點數,虛擬節點越多,分佈越均勻,但程序的分佈式運算越慢
	 */
	public function __construct(FlexiHash_Hasher $hasher=null, $replicas = null){
		// hash方法
		$this->_hasher = $hasher?$hasher: new FlexiHash_Crc32Hasher();
		// 虛擬節點的個數
		if (!empty($replicas)){
			$this->_replicas = $replicas;
		}
	}
	
	/**
	 * 增加節點,根據虛擬節點數,把節點分佈到更多的虛擬位置上
	 */
	public function addTarget($target){
		
		if (isset($this->_targetToPositions[$target])) {
			throw new FlexiHash_Exception("Target $target already exists.");
		}
		
		$this->_targetToPositions[$target] = array();
		
		for ($i = 0; $i < $this->_replicas; $i++) {
			
			// 根據規定的方法hash
			$position = $this->_hasher->hash($target.$i);
			
			// 虛擬節點對應的真實的節點
			$this->_positionToTarget[$position] = $target;
			
			// 真實節點包含的虛擬節點
			$this->_targetToPositions[$target][] = $position;
		}
		
		
		$this->_positionToTargetSorted = false;
		
		// 真實節點個數
		$this->_targetCount++;
		
		return $this;
	}
	
	/**
	 * 添加多個節點
	 * 
	 */
	public function addTargets($targets){
		foreach ($targets as $target){
			$this->addTarget($target);
		}
		return $this;
	}
	
	/**
	 * 移除某個節點
	 * 
	 */
	public function removeTarget($target){
		if (!isset($this->_targetToPositions[$target])){
			throw new FlexiHash_Exception("target $target does not exist\n");
		}
		
		foreach($this->_targetToPositions[$target] as $position){
			unset($this->_positionToTarget[$position]);
		}
		
		unset($this->_targetToPositions[$target]);
		
		$this->_targetCount--;
		
		return $this;
	}
	
	/**
	 * 獲取所有節點
	 * 
	 */
	public function getAllTargets(){
		return array_keys($this->_targetToPositions);
	}
	
	
	/**
	 * 根據key查找hash到的真實節點
	 * 
	 */
	public function lookup($resource){
		$targets = $this->lookupList($resource, 1);
		
		if (empty($targets)){
			throw new FlexiHash_Exception("no targets exist");
		}
		
		return $targets[0];
	}
	
	/**
	 * 查找資源存在的節點
	 * 
	 * 描述:根據要求的數量,返回與$resource哈希後數值相等或比其大並且是最小的數值對應的節點,若不存在或數量不夠,則從虛擬節點排序後的前一個或多個
	 */
	public function lookupList($resource, $requestedCount){
		
		if (!$requestedCount) {
			throw new FlexiHash_Exception('Invalid count requested');
		}
		
		if (empty($this->_positionToTarget)) {
			return array();
		}
		
		// 直接節點只有一個的時候
		if ($this->_targetCount == 1 ){
			return array_unique(array_values($this->_positionToTarget));
		}
		
		// 獲取當前key進行hash後的值
		$resourcePosition = $this->_hasher->hash($resource);
	
		$results = array();
		
		$collect = false;
		
		$this->_sortPositionTargets();
		
		// 查找與$resourcePosition 相等或比其大並且是最小的數
		foreach($this->_positionToTarget as $key => $value){
			
			if (!$collect && $key > $resourcePosition){
				
				$collect = true;
			}
			
			if ($collect && !in_array($value, $results)){
				$results[] = $value;
			}
			
			// 找到$requestedCount 或個數與真實節點數量相同
			if (count($results) == $requestedCount || count($results) == $this->_targetCount){
				return $results;
			}
		}
		// 如數量不夠或者未查到,則從第一個開始,將$results中不存在前$requestedCount-count($results),設置爲需要的節點
		foreach ($this->_positionToTarget as $key => $value){
			if (!in_array($value, $results)){
				$results[] = $value;
			}
			
			if (count($results) == $requestedCount || count($results) == $this->_targetCount){
			
				return $results;
			}
		}
		
		return $results;
		
	}
	
	/**
	 * 根據虛擬節點進行排序
	 */
	private function _sortPositionTargets(){
		if (!$this->_positionToTargetSorted){
			ksort($this->_positionToTarget, SORT_REGULAR);
			
			$this->_positionToTargetSorted = true;
		}
	}
	
}// end class

/**
 * hash方式
 */
interface FlexiHash_Hasher{
	public function hash($string);
}

class FlexiHash_Crc32Hasher implements FlexiHash_Hasher{
	public function hash($string){
		return sprintf("%u",crc32($string));
	}
}


class FlexiHash_Md5Hasher implements FlexiHash_Hasher{
	public function hash($string){
		return substr(md5($string), 0, 8);
	}
}

class FlexiHash_Exception extends Exception{
}

$runData['BEGIN_TIME'] = microtime(true);

for($i=0;$i<10000;$i++) {


	 $targetsArray = array(
	 	"127.0.0.1:11211",
		"127.0.0.1:11212",
		"127.0.0.1:11213",
		"127.0.0.1:11214",
		"127.0.0.1:11215"
	 );
	 $flexiHashObj = new FlexiHash(new FlexiHash_Crc32Hasher(),1);
	 
	 $result = $flexiHashObj->addTargets($targetsArray);
	  $key = md5(mt_rand());
	 $targets = $flexiHashObj->lookup($key);
//	var_dump($targets);
	 
	 

}
	echo "一致性hash:";
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));




$runData['BEGIN_TIME'] = microtime(true); 
$m= new Memcache;
$m->connect('127.0.0.1', 11211); 
for($i=0;$i<10000;$i++) {
        $key = md5(mt_rand());
        $b = $m->set($key, time(), 0, 10);
}
echo "單臺機器:";
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));
?>

測試結果:




發佈了55 篇原創文章 · 獲贊 23 · 訪問量 74萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章