本文介绍使用PHP实现一致性Hash算法。
创建一个FlexiHash类,他有两个成员变量和三个方法:
$serverlist:保存服务器列表。
$isSorted:记录服务器列表是否已经排过序。
addServer:添加一个服务器到服务器列表中;
removeServer:从服务器列表中删除一个服务器;
lookup:在当前的服务器中寻找合适的服务器存放数据。
【示例】:
<span style="font-family:Microsoft YaHei;font-size:18px;"><? class FlexiHash{ private $serverList= array(); private $isSorted =FALSE; public functionaddServer($server){ $hash =mHash($server); if(!isset($this-> serverList[$hash])){ $this-> serverList[$hash] = $server; } $this ->isSorted = FALSE; return TRUE; } functionremoveServer($server){ $hash =mHash($server); if(!isset($this-> serverList[$hash])){ $this-> serverList[$hash] = $server; } $this ->isSorted = FALSE; return TRUE; } functionlookup($key){ $hash =mHash($key); if(!$this-> isSorted){ krsort($this-> serverList,SORT_NUMERIC); $this-> isSorted = TRUE; foreach($this-> serverList as $pos => $server){ if($hash>= $pos) return $server; } return$this -> serverList[count($this -> serverList) -1]; } } } $server = new FlexiHash(); $server ->addServer("192.168.1.1"); $server ->addServer("192.168.1.2"); $server ->addServer("192.168.1.3"); $server ->addServer("192.168.1.4"); $server ->addServer("192.168.1.5"); echo "save key1 inserver:".$server->lookup('key1'); echo "save key2 inserver:".$server->lookup('key2'); echo"+++++++++++++++++++++++++++++++++++++++++++++"; $server ->removeServer("192.168.1.4"); echo "save key1 inserver:".$server->lookup('key1'); echo "save key2 inserver:".$server->lookup('key2'); echo"+++++++++++++++++++++++++++++++++++++++++++++"; $server ->addServer("192.168.1.6"); echo "save key1 inserver:".$server->lookup('key1'); echo "save key2 inserver:".$server->lookup('key2'); echo"+++++++++++++++++++++++++++++++++++++++++++++"; </span>
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u012675743/article/details/46793203