1<?PHP2 3 Header("Content-type:text/html;charset=utf-8");4 5 Interfacehash{6 7 Public function_hash ($str);8 }9 Interfacedistribution{Ten One Public functionLookup$key); A } - /**** - principle and implementation of uniform hash distributed algorithm [PHP implementation] the **/ - classConsistentImplementsHashdistribution{ - #Store the actual node - protected $_nodes=Array(); + #define the number of virtual nodes - protected $mul=64; + #defines a location where an array of records nodes are located A protected $_position=Array(); at #figure out the node - Public function_hash ($str){ - return sprintf('%u ',CRC32($str));//An integer that turns a string into a 32-bit sign - } - #core Functions - Public functionLookup$key){ in #figure out the current node - $point=$this->_hash ($key); to $node= Current($this->_position);//take the smallest node on the ring first + #Loop so node - foreach($this->_nodes as $k=$v){ the #find the number of nodes where the current node is located, if no description is found is greater than so the node is on the smallest node * if($point<=$k){ $ $node=$v;Panax Notoginseng Break; - } the } + return $node; A } the #Add a node + Public functionAddNode ($node){ - #store in array go to Arrar ([Key=>val]) $ //$this->_nodes[$this->_hash ($node)]= $node; $ for($i= 0;$i<$this->mul;$i++) { - $this->_position[$this->_hash ($node.‘ -‘.$i)]=$node; - } the $this-_sortnode (); - Wuyi } the #Delete a node - Public functionDelnode ($node){ Wu foreach($this->_position as $k=$v) { - if($v==$node){ About unset($this->_position[$k]); $ } - } - } - #Sort A protected function_sortnode () { + #sort_regular Sort by key size the Ksort($this->_position,sort_regular); - } $ #Print out all the virtual nodes the Public functiongetnodes () { the Var_dump($this-_position); the } the } - $con=Newconsistent (); in $con->addnode (' a '); the $con->addnode (' B '); the $con->addnode (' C '); About the the Echo' Currently so the server is as follows:<br/> '; the $con-getnodes (); + Echo' <br/> the current build calculation of the HSAs landing is '.$con->_hash (' name '). ' <br/> '; - Echo' Name '. ' In the '.$con->lookup (' name '). ' Node ';
Principle and implementation of a distributed hashing algorithm with Memcached consistency [PHP implementation]