Home > Backend Development > PHP Tutorial > 基于php的一个最简略的memcache的分布式算法

基于php的一个最简略的memcache的分布式算法

WBOY
Release: 2016-06-13 11:59:00
Original
814 people have browsed it

基于php的一个最简单的memcache的分布式算法

首先,核心函数是这个

function mHash($key){

$md=substr(md5($key),0,8);

$seed=31;

  $hash=0;

for($i=0;$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');

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template