欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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>";

简单记录下实现的类,各位有则取之。