?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;$i8;$i++){
$hash = $hash*$seed+ord($md5{$i}); //ord 返回ascii值
$i++;
}
return $hash0x7FFFFFFF; //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相关内容感兴趣的读者可查看本站专题:《php加密方法总结》、《PHP编码与转码操作技巧汇总》、《PHP数学运算技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP数据结构与算法教程》、《php程序设计算法总结》及《php正则表达式用法总结》