This article describes the implementation of a consistent hash algorithm using PHP.
Create a Flexihash class that has two member variables and three methods:
$serverlist: Save the list of servers.
$isSorted: Records whether the server list has been sequenced.
Addserver: Add a server to the server list;
Removeserver: Remove a server from the server list;
Lookup: Find the right server to store data in the current server.
"Example":
<span style= "Font-family:microsoft yahei;font-size:18px;" ><? Class flexihash{Private $serverList = Array (); Private $isSorted =false; Public Functionaddserver ($server) {$hash =mhash ($server); if (!isset ($this-serverlist[$hash]) {$this, serverlist[$hash] = $server; } $this->issorted = FALSE; return TRUE; } functionremoveserver ($server) {$hash =mhash ($server); if (!isset ($this-serverlist[$hash]) {$this, serverlist[$hash] = $server; } $this->issorted = FALSE; return TRUE; } functionlookup ($key) {$hash =mhash ($key); if (! $this-issorted) { Krsort ($this-serverlist,sort_numeric); $this-issorted = TRUE; foreach ($this-serverlist as $pos = + $server) {if ($hash >= $pos) return $server ; } return$this-Serverlist[count ($this-ServerList)-1]; }}} $server = new Flexihash (); $server->addserver ("192.168.1.1"); $server->addserver ("192.168.1.2"); $server->addserver ("192.168.1.3"); $server->addserver ("192.168.1.4"); $server->addserver ("192.168.1.5"); echo "Save Key1 Inserver:". $server->lookup (' Key1 '); echo "Save Key2 Inserver:". $server->lookup (' Key2 '); echo "+++++++++++++++++++++++++++++++++++++++++++++"; $server->removeserver ("192.168.1.4"); echo "Save Key1 Inserver:". $server->lookup (' Key1 '); echo "Save Key2 Inserver: ". $server->lookup (' Key2 '); echo "+++++++++++++++++++++++++++++++++++++++++++++"; $server->addserver ("192.168.1.6"); echo "Save Key1 Inserver:". $server->lookup (' Key1 '); echo "Save Key2 Inserver:". $server->lookup (' Key2 '); echo "+++++++++++++++++++++++++++++++++++++++++++++"; </span>
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
An example of a consistent hash distribution algorithm