The following uses PHP to implement a consistent hash distribution algorithm.
Create a Conhash class that has two member variables and three member methods.
Variable:
seRveRLIsT//WarrantySaveServiceServicesDevicecolumnTable IsSorted//Records whether the server list has been sequenced.
Method:
Addserver: Add a server to the server list
Removeserver: Remove a server from the server list
Lookup: Locate the appropriate server to hold data from the current server list.
The code is as follows:
<?php class ConHash { private $serverList = array(); private $isSorted = false; function addServer($server) {...} function removeServer($server) {...} function lookup($key) {...}}?>
1) Addserver Method implementation
function addServer($server) { $hash = mhash(MHASH_MD5,$server); if(!isset($serverList[$hash])) { $this->serverList[$hash]=$server; } $this->isSorted = false; return true;} function removeServer($server) { $hash=mhash(MHASH_MD5,$server); if(isset($this->serverList[$hash])) { unset($this->serverList[$hash]); } $this->isSorted = false; return true;}
3) Lookup Method implementation
function lookup($key) { $hash=mhash(MHASH_MD5,$key); if(!$this->isSorted) { krsort($this->serverList); $this->isSorted=true; } foreach($this->serverList as $pos =>$server) { if($hash>=$pos) { return $server; } } return $this->serverList[count($this->serverList)-1];}
The Lookup method first calculates the hash value of the key through the Mhash function, then determines whether the server list is ordered, or, if not, the list of servers is sorted in reverse order. The reverse sort function is to convert the list of servers to a counterclockwise ring. Finally, traverse the list of servers to find a suitable server to return.
4) Test Code
$hserver = new ConHash();$hserver->addServer("192.168.1.1");$hserver->addServer("192.168.1.2");$hserver->addServer("192.168.1.3");$hserver->addServer("192.168.1.4");$hserver->addServer("192.168.1.5");echo "保存 key1 在 server:",$hserver->lookup(‘key1‘);echo "保存 key2 在 server:",$hserver->lookup(‘key2‘);echo ‘===================================‘;$hserver->removeServer("192.168.1.2");$hserver->removeServer("192.168.1.1");echo "保存 key1 在 server:",$hserver->lookup(‘key1‘);echo "保存 key2 在 server:",$hserver->lookup(‘key2‘);echo ‘===================================‘;$hserver->addServer("192.168.1.6");echo "保存 key1 在 server:",$hserver->lookup(‘key1‘);echo "保存 key2 在 server:",$hserver->lookup(‘key2‘);
The test results are random, and the results may vary on different machines. But this example explains the consistency hash algorithm.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Implementation example of PHP with consistent hash algorithm