1. 程式人生 > >一致性雜湊的PHP實現

一致性雜湊的PHP實現

 一致性雜湊的PHP實現

<?php
// 需要一個把字串轉成整數的介面
interface hasher {
	public function _hash($str);
}
interface distribution {
	public function lookup($key);
}
class Consistent implements hasher,distribution {
	protected $_nodes = array();
	protected $_postion = array();
	protected $_mul = 64;             //每個節點對應 64 個虛節點
	public function _hash($str) {
	return sprintf('%u',crc32($str)); // 把字串轉成 32 位符號整數
}
// 核心功能
public function lookup($key) {
	$point = $this->_hash($key);
	$node = current($this->_postion); //先取圓環上最小的一個節點,當成結果
	foreach($this->_postion as $k=>$v) {
		if($point <= $k) {
			$node = $v;
			break;
		}
	}
	reset($this->_postion);
	return $node;
}
// 新增一個節點會自動新增64個虛節點
public function addNode($node) {
	if(isset($this->nodes[$node])) {
		return;
	}
	for($i=0; $i<$this->_mul; $i++) {
		$pos = $this->_hash($node . '-' . $i);
		$this->_postion[$pos] = $node;
		$this->_nodes[$node][] = $pos;
	}
	$this->_sortPos();
}
// 迴圈所有的虛節點,誰的值==指定的真實節點 ,就把他刪掉
public function delNode($node) {
	if(!isset($this->_nodes[$node])) {
		return;
	}
	foreach($this->_nodes[$node] as $k) {
		unset($this->_postion[$k]);
	}
		unset($this->_nodes[$node]);
	}
	protected function _sortPos() {
		ksort($this->_postion,SORT_REGULAR);
	}
}
// 測試
$con = new Consistent();
$con->addNode('a');
$con->addNode('b');
$con->addNode('c');
$key = '121';
	echo '此 key 落在',$con->lookup($key),'號節點';
?>