原理
参考 https://www.bilibili.com/video/av25184175?from=search&seid=5169155263985611919 讲的非常清晰
代码
class consistencyHash
{
protected $serverNodes = array();
protected $virtualNum = 64;
protected $virtualNodes = array();
/**
* hash实现
* @param $str
* @return int
*/
public function _hash($str)
{
return sprintf('%u', crc32($str));
}
/**
* 查找key所属的节点
* @param $key
* @return mixed
*/
public function lookup($key)
{
$point = $this->_hash($key);
$current = current($this->serverNodes);
foreach ($this->virtualNodes as $key => $value) {
if ($point <= $key) {
$current = $value;
break;
}
}
return $current;
}
/**
* 添加节点
* @param $node
*/
public function addNode($node)
{
for ($i = 0; $i <= $this->virtualNum; $i++) {
$virtualNode = $node . "-" . $i;
$this->virtualNodes[$this->_hash($virtualNode)] = $node;
}
$this->sortNodes();
}
/**
* 对node进行排序
*/
private function sortNodes()
{
ksort($this->serverNodes);
}
public function debug(){
echo "virtualNodes :" . json_encode($this->virtualNodes);
echo "\n\r";
}
}