<?php
interface hash
{
public function _hash($str);
}
interface distribution
{
public function lookup($key);
}
class Consistent implements hash,distribution
{
protected $_postion = [];
protected $_mul = 64;
public function _hash($str){
return sprintf('%u',crc32($str));
}
public function lookup($key){
$point = $this->_hash($key);
//先取圆环上最小的一个节点
$node = current($this->_postion);
foreach($this->_postion as $k=>$v){
if($point <= $k){
$node = $v;
break;
}
}
return $node;
}
//添加节点
public function addNode($node){
for($i = 0;$i<$this->_mul;$i++){
$this->_postion[$this->_hash($node . '-' . $i)] = $node;
}
$this->_sortPos();
}
//删除节点
public function delNode($node){
foreach($this->_postion as $k=>$v){
if($v == $node){
unset($this->_postion[$k]);
}
}
}
//排序节点
protected function _sortPos(){
ksort($this->_postion,SORT_REGULAR);
}
public function printPosition(){
print_r($this->_postion);
}
}
//添加节点
$con = new Consistent();
$con->addNode('a');
$con->addNode('b');
$con->addNode('c');
//删除节点
$con->delNode('b');
echo '所有的服务器如下<br />';
$con->printPosition();
$key = 'title';
echo '当前的键计算的hash落点是' . $con->_hash($key). '<br />';
echo '应该落在'.$con->lookup($key) .'号服务器';