目的:无法阻止宕机的缓存被使用,但可以尽可能保证正常的服务器一切如常。[取余的方式一旦有机器增减,数据位置100%失效,缓存雪崩]
场景:缓存服务器集群
原理:节点在0-2^32圜环上占位,每次使用HASH(KEY)无限趋近的 节点作为落地。【虚拟节点的目的是为了尽可能保持数据平衡,3台机器很容易失衡导致某一台机器数据过载。】

<?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;

?>