目的:沒法阻止宕機的緩存被使用,但能夠儘量保證正常的服務器一切如常。[取餘的方式一旦有機器增減,數據位置100%失效,緩存雪崩]
場景:緩存服務器集羣
原理:節點在0-2^32圜環上佔位,每次使用HASH(KEY)無限趨近的 節點做爲落地。【虛擬節點的目的是爲了儘量保持數據平衡,3臺機器很容易失衡致使某一臺機器數據過載。】php
<?phpnode
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");ide
echo $obj->getNode(111) . PHP_EOL;
echo $obj->getNode(222) . PHP_EOL;
echo $obj->getNode(222) . PHP_EOL;this
?>code