本文實例講述了PHP實現(xiàn)的服務器一致性hash分布算法。分享給大家供大家參考,具體如下:
?php
/**
* 對服務器進行一致性hash分布算法
*/
class HashRing
{
private $servers = array();
private $nodeList = array();
private $nodeHashList = array();
private $nodeTotalNum = 0;
private $virtualNodeNum = 32;
private $keyHash = '';
public function __construct($servers)
{
$this->servers = $servers;
foreach ($servers as $server) {
for ($i = 0; $i $this->virtualNodeNum; $i++) {
$this->nodeList[sprintf("%u", crc32($server.'-'.$i))] = array($server, $i);
}
}
ksort($this->nodeList);
$this->nodeHashList = array_keys($this->nodeList);
}
private function getNodeIndex($key)
{
$this->keyHash = sprintf("%u", crc32($key));
if ($this->keyHash > end($this->nodeHashList)) {
$this->keyHash = $this->keyHash % end($this->nodeHashList);
}
if ($this->keyHash = reset($this->nodeHashList)) {
return 0;
}
$this->nodeTotalNum = count($this->nodeHashList);
return $this->binaryChopIndex(0, $this->nodeTotalNum);
}
private function binaryChopIndex($l=0, $r=0)
{
if ($l $r) {
$avg = intval(($l+$r) / 2);
if ($this->nodeHashList[$avg] == $this->keyHash) {
return $avg;
} elseif ($this->keyHash $this->nodeHashList[$avg] ($avg > 0)) {
return $this->binaryChopIndex($l, $avg-1);
} else {
return $this->binaryChopIndex($avg+1, $r);
}
} else {
return $l;
}
}
public function getServersByKey($key, $num=1)
{
$index = $this->getNodeIndex($key);
$server = $this->nodeList[$this->nodeHashList[$index]];
if ($num == 1) {
return $server[0];
}
if ($num >= count($this->servers)) {
$num = count($this->servers);
}
$result = array($server[0]);
for ($i=$index+1; true; $i++) {
if ($i >= $this->nodeTotalNum) {
$i = 0;
}
$nextServer = $this->nodeList[$this->nodeHashList[$i]];
if (!in_array($nextServer[0], $result)) {
$result[] = $nextServer[0];
}
if (count($result) == $num) {
break;
}
}
return $result;
}
}
//示例
$servers = array(
'127.0.0.1:11211',
'127.0.0.1:11212',
'127.0.0.1:11213',
'127.0.0.1:11214',
'127.0.0.1:11215'
);
$obj = new HashRing($servers);
$servers = $obj->getServersByKey('testkey', 2);
print_r($servers);
echo "\n";
運行結果:
Array
(
[0] => 127.0.0.1:11214
[1] => 127.0.0.1:11211
)
PS:這里再為大家提供2款hash相關在線工具供大家參考使用:
在線散列/哈希算法加密工具:
http://tools.jb51.net/password/hash_encrypt
在線MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php加密方法總結》、《PHP編碼與轉碼操作技巧匯總》、《PHP數(shù)學運算技巧總結》、《PHP數(shù)組(Array)操作技巧大全》、《php字符串(string)用法總結》、《PHP數(shù)據(jù)結構與算法教程》、《php程序設計算法總結》及《php正則表達式用法總結》
希望本文所述對大家PHP程序設計有所幫助。
您可能感興趣的文章:- PHP哈希表實現(xiàn)算法原理解析
- PHP實現(xiàn)的一致性哈希算法完整實例
- PHP內核探索:哈希表碰撞攻擊原理
- PHP中創(chuàng)建和驗證哈希的簡單方法實探
- php內核解析:PHP中的哈希表
- php-perl哈希算法實現(xiàn)(times33哈希算法)
- PHP 5.5 創(chuàng)建和驗證哈希最簡單的方法詳解
- 一致性哈希算法以及其PHP實現(xiàn)詳細解析
- 如何用PHP實現(xiàn)分布算法之一致性哈希算法