当前位置: 首页 > 后端技术 > PHP

[PHP]PHP实现Hash环-Hash一致性原则

时间:2023-03-29 15:19:56 PHP

引用大佬文章:HashringclassconsistTenHash{public$serverList=[];//服务器列表public$virtualPos=[];//虚拟节点位置public$virtualPosNum=2;//每个节点有2个虚拟节点/**使用循环冗余算法计算十进制校验值**/publicfunctioncHash($str){$str=md5($str);返回sprintf('%u',crc32($str));}/**从当前服务器列表中寻找合适的服务器进行存储**/publicfunctionlookup($key){$point=$this->cHash($key);$finalServer=current($this->virtualPos);foreach($this->virtualPosas$pos=>$server){if($point<=$pos){$finalServer=$server;休息;}}重置($this->virtualPos);返回$finalServer;}/**添加一个服务器节点**/publicfunctionaddServer($server){if(!isset($this->serverList[$server])){for($i=0;$i<$this->virtualPosNum;$i++){$pos=$this->cHash($server.'_'.$i);$this->virtualPos[$pos]=$server;$this->serverList[$server][]=$pos;}ksort($this->virtualPos,SORT_NUMERIC);}返回真;}/**删除一个服务器节点**/publicfunctiondelServer($key){if(isset($this->serverList[$key])){//删除节点foreach($this->serverList[$key]作为$pos){unset($this->virtualPos[$pos]);}//删除对应的serverunset($this->serverList[$key]);}返回真;}}测试代码://添加五个服务器$consisTenHash=newconsistTenHash();$consisTenHash->addServer('127.0.0.1');$consisTenHash->addServer('127.0.0.2');$consisTenHash->addServer('127.0.0.3');$consisTenHash->addServer('127.0.0.4');$consisTenHash->addServer('127.0.0.5');//显示服务器的位置var_dump($consisTenHash->serverList);//添加Key,找到存放的服务器位置var_dump($consisTenHash->lookup("zxxxxx"));var_dump($consisTenHash->lookup("rrrrrrrrrr-c-1i312"));var_dump($consisTenHash->lookup("shhjjaaaaaaa"));var_dump($consisTenHash->lookup("blue-ssalllllllkk"));var_dump($consisTenHash->lookup("unset-bjhujka"));var_dump($consisTenHash->lo