Simple example of PHP implementing common hash distributed algorithm

  • 2021-10-25 06:09:31
  • OfStack

In this paper, an example is given to describe the implementation of common hash distributed algorithm by PHP. Share it for your reference, as follows:


<?php
/*
 *  Ordinary hash Distributed algorithm 
 * @param $key
 * @return int
 */
class Hash{
  protected $_serverList = array();
  public function __construct($_serverList){
    if(is_array($_serverList)){
      $this->_serverList = $_serverList;
    }else{
      return false;
    }
  }
  // Pass hash Algorithm return 1 Integer value 
  protected function myHash($key){
    $md5 = substr(md5($key),0,8);
    $seed = 31; // Seed value 
    $hash=0;
    for($i=0;$i<8;$i++){
      $hash = $hash*$seed+ord($md5{$i}); //ord  Return ascii Value 
      $i++;
    }
    return $hash&0x7FFFFFFF; //0x7FFFFFFF Represents the maximum value 
  }
  public function getServer($key){
    $servers = $this->_serverList;
    $rs = $servers[$this->myHash($key)%(count($servers))];
    return $rs;
  }
}
$servers = array(
  array('host'=>'192.168.1.1','port'=>6397),
  array('host'=>'192.168.1.2','port'=>6397),
  array('host'=>'192.168.1.3','port'=>6397),
  array('host'=>'192.168.1.4','port'=>6397),
  array('host'=>'192.168.1.5','port'=>6397),
  array('host'=>'192.168.1.6','port'=>6397),
  array('host'=>'192.168.1.7','port'=>6397),
);
$key = 'TheKey'.rand(0,99999);
$value = 'TheValue';
$hash = new Hash($servers);
if($hash){
  $server = $hash->getServer($key);
  // $memcached = new Memcached($sc);
  // $memcached->set($key,$value);
}
?>

PS: Here are two online tools related to hash for your reference:

Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt

Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 Encryption Tool:
http://tools.ofstack.com/password/hash_md5_sha

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of php Encryption Methods", "Summary of PHP Encoding and Transcoding Operation Skills", "Summary of PHP Mathematical Operation Skills", "Encyclopedia of PHP Array (Array) Operation Skills", "Summary of php String (string) Usage", "Tutorial of PHP Data Structure and Algorithm", "Summary of php Programming Algorithm" and "Summary of php Regular Expression Usage"

I hope this article is helpful to everyone's PHP programming.


Related articles: