标签:unset i++ sprint key echo 服务器 break code private
目的:无法阻止宕机的缓存被使用,但可以尽可能保证正常的服务器一切如常。[取余的方式一旦有机器增减,数据位置100%失效,缓存雪崩]<?php
class consistentHash
{
private $nodes;
private $virtualNodes;
const VIRTUAL_NODES_NUM = 2;
public function commonHash($key)
{
return sprintf("%u", crc32($key));
}
public function addNode($node)
{
if (isset($this->nodes[$node])) {
return;
}
for ($i = 0; $i <= self::VIRTUAL_NODES_NUM; $i++) {
$hash = $this->commonHash($node . ‘-‘ . $i);
$this->virtualNodes[$hash] = $node;
$this->nodes[$node][] = $hash;
}
ksort($this->virtualNodes, SORT_REGULAR);
}
public function delNode($node)
{
if (!isset($this->nodes[$node])) {
return;
}
foreach ($this->nodes[$node] as $k => $v) {
unset($this->virtualNodes[$v]);
}
unset($this->nodes[$node]);
}
public function getNode($key)
{
$hash = $this->commonHash($key);
$res = current($this->virtualNodes);
foreach ($this->virtualNodes as $k => $v) {
if ($hash <= $k) {
$res = $v;
break;
}
}
reset($this->virtualNodes);
return $res;
}
}
$obj = new consistentHash();
$obj->addNode("192.168.1.1");
$obj->addNode("192.168.1.2");
$obj->addNode("192.168.1.3");
$obj->addNode("192.168.1.4");
$obj->addNode("192.168.1.5");
echo $obj->getNode(111) . PHP_EOL;
echo $obj->getNode(222) . PHP_EOL;
echo $obj->getNode(222) . PHP_EOL;
?>
标签:unset i++ sprint key echo 服务器 break code private
原文地址:https://blog.51cto.com/jhomephper/2454883