本文实例讲述了PHP实现普通hash分布式算法。分享给大家供大家参考,具体如下:<?php/*
本文实例讲述了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);
}
?>
PS:这里再为大家提供2款hash相关在线工具供大家参考使用:
在线散列/哈希算法加密工具: http://tools.jb51.net/password/hash_encrypt
在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具: http://tools.jb51.net/password/hash_md5_sha
PHP hash 分布式算法