<?php
class ConsistentHash{
private $virtual = 10;
protected $serverList = array();
protected $serverNode = array();
protected function getHash($key){
return sprintf("%u", crc32(md5($key)));
}
public function addServer($server){
for($i = 1; $i <= $this->virtual; $i ++){
$index = $this->getHash($server."@".$i);
$this->serverList[$index] = $server;
$this->serverNode[$server][] = $index;
}
ksort($this->serverList, SORT_NUMERIC);
return $this;
}
public function getServer($key){
$point = $this->getHash($key);
$server = current($this->serverList);
foreach($this->serverList as $index => $value){
if($point >= $index){
$server = $value;
}
}
reset($this->serverList);
return $server;
}
public function subServer($server){
if(isset($this->serverNode[$server])){
foreach($this->serverNode[$server] as $index){
unset($this->serverList[$index]);
}
unset($this->serverNode[$server]);
}
return $this;
}
}
$data = new ConsistentHash;
$data->addServer("192.168.1.1")->addServer("192.168.1.2")->addServer("192.168.1.3")->addServer("192.168.1.4")->addServer("192.168.1.5")->addServer("192.168.1.6")->addServer("192.168.1.7")->addServer("192.168.1.8")->addServer("192.168.1.9")->addServer("192.168.1.10");
print_r($data);
echo $data->getServer("data1");
echo PHP_EOL;
echo $data->getServer("data2");
echo PHP_EOL;
echo $data->getServer("data3");
echo PHP_EOL;
echo $data->getServer("data4");
echo PHP_EOL;
echo $data->getServer("data5");
echo PHP_EOL;
echo $data->getServer("data6");
echo PHP_EOL;
echo $data->getServer("data7");
echo PHP_EOL;
echo $data->getServer("data8");
echo PHP_EOL;
echo $data->getServer("data9");
echo PHP_EOL;
echo $data->getServer("data10");
echo PHP_EOL;
echo $data->getServer("data11");
$data->subServer("192.168.1.4")->subServer("192.168.1.2")->subServer("192.168.1.3")->subServer("192.168.1.1");
echo PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL.PHP_EOL;
echo $data->getServer("data1");
echo PHP_EOL;
echo $data->getServer("data2");
echo PHP_EOL;
echo $data->getServer("data3");
echo PHP_EOL;
echo $data->getServer("data4");
echo PHP_EOL;
echo $data->getServer("data5");
echo PHP_EOL;
echo $data->getServer("data6");
echo PHP_EOL;
echo $data->getServer("data7");
echo PHP_EOL;
echo $data->getServer("data8");
echo PHP_EOL;
echo $data->getServer("data9");
echo PHP_EOL;
echo $data->getServer("data10");
echo PHP_EOL;
echo $data->getServer("data11");