memcached缓存服务器一致性哈希分布部署类
程序员文章站
2024-03-19 22:45:10
...
class FlexHash{
private $server_list = array();
private $is_sort = false;
public function add_server($server)
{
$hash = mhash(MHASH_MD5,$server);
if(!isset($this->server_list[$hash])){
$this->server_list[$hash] = $server;
}
$this->is_sort = false;
return true;
}
public function remove_server($server)
{
$hash = mhash(MHASH_MD5,$server);
if(isset($this->server_list[$hash])){
unset($this->server_list[$hash]);
}
$this->is_sort = false;
return true;
}
public function look_up($key)
{
$hash = mhash(MHASH_MD5,$key);
if(!$this->is_sort){
krsort($this->server_list,SORT_NUMERIC);
$this->is_sort = true;
}
foreach ($this->server_list as $item => $value) {
if($hash >= $value) return $value;
}
return $this->server_list[count($this->server_list) - 1];
}
}
//echo $hash = mhash(MHASH_MD5,'1.2.3.4');
$server = new FlexHash();
$server->add_server('1.2.3.4');
$server->add_server('5.6.7.8');
$server->add_server('9.10.11.12');
$server->add_server('13.14.15.16');
$server->add_server('17.18.19.20');
$server->add_server('21.22.23.24');
$server->add_server('25.26.27.28');
echo "save 1 in ".$server->look_up('key1')."<br>";
echo "save 2 in ".$server->look_up('key2')."<br>";
$server->remove_server("21.22.23.24");
echo "save 1 in ".$server->look_up('key1')."<br>";
echo "save 2 in ".$server->look_up('key2')."<br>";
$server->add_server('29.30.31.32');
echo "save 1 in ".$server->look_up('key1')."<br>";
echo "save 2 in ".$server->look_up('key2')."<br>";
简单记录下实现的类,各位有则取之。
上一篇: Nginx负载均衡之一致性哈希算法
下一篇: 插入排序算法——python实现