PHP实现普通hash分布式算法简单示例

时间:2022-09-01 19:51:32

本文实例讲述了PHP实现普通hash分布式算法。分享给大家供大家参考,具体如下:

<?php
/*
 * 普通hash分布式算法
 * @param $key
 * @return int
 */
class Hash{
  protected $_serverList = array();
  public function __construct($_serverList){
    if(is_array($_serverList)){
      $this->_serverList = $_serverList;
    }else{
      return false;
    }
  }
  //通过hash算法返回一个整数值
  protected function myHash($key){
    $md5 = substr(md5($key),0,8);
    $seed = 31; //种子值
    $hash=0;
    for($i=0;$i<8;$i++){
      $hash = $hash*$seed+ord($md5{$i}); //ord 返回ascii值
      $i++;
    }
    return $hash&0x7FFFFFFF; //0x7FFFFFFF表示最大值
  }
  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);
}
?>

希望本文所述对大家PHP程序设计有所帮助。