首先,核心函数是这个
function mHash($key){
$md=substr(md5($key),0,8);
$seed=31;
$hash=0;
for($i=0;$i<8;$i++){
$hash=$hash*$seed+ord($md5{$i});
}
return $hash & 0x7FFFFFFF;
}
class HashServer{
private $serverlist;
private $issorted=false;
function addServer($server){
$hash=mHash($server);
if(!isset($this->serverlist[$hash])){
$this->serverlist[$hash]=$server;
}
return true;
}
function getKeyServer($key){
$hash=mHash($key);
if(!this->issorted){
ksort($this->serverlist,SORT_NUMERIC);
}
foreach($this->serverlist as $k=>$v){
if($hash>=$k) return $v;
}
return $this->serverlist[count($this->serverlist)-1];
}
}
//下面开始测试
$hs=new HashServer();
$hs->addServer(‘192.168.1.1‘);
$hs->addServer(‘192.168.1.2‘);
$hs->addServer(‘192.168.1.3‘);
echo $hs->getKeyServer(‘key1‘);
echo $hs->getKeyServer(‘key2‘);
echo $hs->getKeyServer(‘key3‘);
基于php的一个最简单的memcache的分布式算法,布布扣,bubuko.com