版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41179401/article/details/84840219
一致性哈希的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),'号节点';
?>