PHP简单实现Memcache或者Redis一致性Hash分布式集群算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/flyfreelyit/article/details/80341505
<?php
/*
PHP简单实现Memcache或者Redis一致性Hash分布式集群算法
*/
class Consistent{
protected $position = array();
protected $server;

// 统一的Hash算法
public function hash($str){
return sprintf("%u",crc32($str));
}

// 计算$key分布到哪台服务器上
public function lookUp($key){
foreach($this->position as $k=>$v){
if($this->hash($key)<=$k){
$this->server = $v;
break;
}
}
return $this->server;
}

// 添加节点
public function addServer($server){
if(!isset($this->position[$this->hash($server)])){
$this->position[$this->hash($server)] = $server;
}
$this->sortPosition();
}

// 按顺时针方向成环
private function sortPosition(){
ksort($this->position);
}

// 打印节点,调试用
public function print(){
foreach($this->position as $k=>$v){
echo $k." => ".$v.PHP_EOL;
}
}

}

$c = new Consistent();

$c->addServer("192.168.1.1");
$c->addServer("192.168.1.2");
$c->addServer("192.168.1.3");
$c->addServer("192.168.1.4");
$c->addServer("192.168.1.5");
$c->addServer("192.168.1.6");

for($i=0;$i<20;$i++){
echo "user:".$i." => ".$c->lookUp("user:".$i) . PHP_EOL;
}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页