In a distributed system, if a business can be processed by multiple identical nodes, it is easy to think of hashing the business request into these nodes processing, such as the Memecache cache and other distributed cluster applications, if it is simply used, does not involve the user state and other information, you can directly adopt the modulus algorithm. Under normal circumstances, the modulus algorithm seems to be good, but once the node or one of the nodes on the outage, the hit rate will be sharply reduced, so the algorithm in this case the disadvantage is obvious, to this end, in 1997, a distributed hash (DHT) implementation algorithm proposed by MIT. Specific algorithm introduction I don't have much here, I need to know. See this article: http://www.cnblogs.com/haippy/archive/2011/12/10/2282943.html
The following is a simple implementation of PHP
Class hash{//placement set, can be cached private $_locations = Array (); Number of virtual nodes private $virtualNodeNum = 24; Maintenance of another node and virtual node corresponding relationship, easy to delete private $_nodes; Converts a string into a digital private function _hash ($STR) {return sprintf ('%u ', CRC32 ($STR)); /** * Find the machine location where the string is located * @param $str * @return bool|mixed */Public Function getLocation ($STR) { if (Empty ($this->_locations)) {return false; }else{$position = $this->_hash ($STR); The default takes the first node $node = current ($this->_locations); foreach ($this->_locations as $k + $v) {//If the current position is less than or equal to one node in the node group, then the current position pair should be node if ($positio N <= $k) {$node = $v; Break }} return $node; }}/** * Add a node * @param $node */Public Function AddNode ($node) {//Generate virtual node for ($i = 0, $i < $this->virtualnodenum; $i + +) { $tmp = $this->_hash ($node. $i); $this->_locations[$tmp] = $node; $this->_nodes[$node] [] = $tmp; }//Sort the nodes Ksort ($this->_locations,sort_numeric); }/** * Deletes a node * @param $node */Public Function Deletenode ($node) {foreach ($this->_nodes[ $node] as $v) {unset ($this->_locations[$v]); } }}
A simple implementation of PHP consistent hashing algorithm