PHP实现普通hash分布式算法简单示例
本文实例讲述了PHP实现普通hash分布式算法。分享给大家供大家参考,具体如下:
_serverList=$_serverList; }else{ returnfalse; } } //通过hash算法返回一个整数值 protectedfunctionmyHash($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表示最大值 } publicfunctiongetServer($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=newHash($servers); if($hash){ $server=$hash->getServer($key); //$memcached=newMemcached($sc); //$memcached->set($key,$value); } ?>
PS:这里再为大家提供2款hash相关在线工具供大家参考使用:
在线散列/