1. 程式人生 > >一致性哈希算法PHP測試片段

一致性哈希算法PHP測試片段

protect add array ntp prot class ech printf bre

<?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();

一致性哈希算法PHP測試片段