一致性哈希算法PHP测试片段

<?php
header('Content-type: text/html; charset=utf8');
# 抽象接口
interface hash{
public function _hash($str);
}
interface distribution{
public function lookup($key);
}

# hash 算法实例
class Consistent implements hash,distribution {
protected $point_num = 64;
protected $posi = array();
protected $server;

#计算一个hash值
public function _hash($str){
return sprintf('%u',crc32($str));
}

# 计算key分布到的服务器
public function lookup($key){
foreach($this->posi as $k=>$v){
if ($this->_hash($key) <= $k ){
$this->server = $v;
break;
}
}
return $this->server;
}

# 添加服务节点
public function addServer($server){
for ($i=1;$i<=$this->point_num;$i++){
$this->posi[$this->_hash($server.'_'.$i)] = $server;
}
$this->sortPosi();
}

#排序定位点
public function sortPosi(){
ksort($this->posi);
}

#打印定位点
public function printPosi(){
echo '<pre>';
print_r($this->posi);
}
}

$hash = new Consistent();
$hash->addServer('a');
$hash->addServer('b');
$hash->addServer('c');

#test hash
$key = 'abc';
$server = $hash->lookup($key);
echo $key.'对应的服务器是:'.$Server.' &nbsp;&nbsp;对应的hash值是:'.$hash->_hash($key);
echo '<hr />';
$hash->printPosi();

posted @ 2017-08-31 10:42  盛碗米饭  阅读(176)  评论(0编辑  收藏  举报