博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
php实现一致性hash算法
阅读量:6568 次
发布时间:2019-06-24

本文共 2870 字,大约阅读时间需要 9 分钟。

 

使用php实现一致性hash算法

hasher = isset($hasher) ? $hasher : new Crc32Hasher(); isset($replicas) && $this->replicas = $replicas; } public function addTarget($target, $weight = 1) { $positions = array(); $existPositions = array_keys($this->positionTargetMap); for ($i = 0; $i < $this->replicas * $weight; $i++) { //find an position not in exist positions $suffix = ''; do { $suffix .= $i; $position = $this->hasher->hash($target.''.$suffix); } while (in_array($position, $existPositions)); //record position's target $this->positionTargetMap[$position] = $target; //collect position $positions[] = $position; } //sort position ksort($this->positionTargetMap); //record target's positions $this->targetPositionsMap[$target] = $positions; } public function removeTarget($target) { if (!isset($this->targetPositionsMap[$target])) { throw new Exception('remove not exists target: '.$target); } $positions = $this->targetPositionsMap[$target]; //remove target's positions unset($this->targetPositionsMap[$target]); //remove position's target foreach ($positions as $position) { unset($this->positionTargetMap[$position]); } } public function lookup($resource) { return $this->lookupList($resource, 1)[0]; } public function lookupList($resource, $count) { if ($this->isTargetsEmpty()) { throw new Exception('lookup targets empty'); } if ($count > count($this->targetPositionsMap)) { throw new Exception('lookup targets not enough'); } $targetList = array(); $hash = $this->hasher->hash($resource); //find in the above positions foreach ($this->positionTargetMap as $position => $t) { if (count($targetList) == $count) { break; } if ($hash >= $position) { $targetList[] = $t; } } //find in the below positions if (count($targetList) < $count) { foreach ($this->positionTargetMap as $position => $t) { if (count($targetList) == $count) { break; } $targetList[] = $t; } } return $targetList; } public function isTargetsEmpty() { return count($this->targetPositionsMap) == 0; } public function addTargets($targets) { foreach ($targets as $target) { $this->addTarget($target); } } public function removeTargets($targets) { foreach ($targets as $target) { $this->removeTarget($target); } }}

 

 

转载于:https://www.cnblogs.com/livepeace/p/8952045.html

你可能感兴趣的文章
【参与有奖】您用的MySQL、MongoDB、Redis等服务被勒索过吗?
查看>>
Java核心技术卷I基础知识1.2.6 体系结构中立
查看>>
Libvirt 虚拟化库介绍
查看>>
《Spring 5 官方文档》26. JMS(一)
查看>>
《Python Cookbook(第2版)中文版》——1.11 检查一个字符串是文本还是二进制
查看>>
Tkinter之Label
查看>>
PostgreSQL merge json的正确姿势
查看>>
java反射
查看>>
【IOS-COCOS2D游戏开发之二】COCOS2D 游戏开发资源贴(教程以及源码)
查看>>
nodejs安装记录
查看>>
Android2.2 API 中文文档系列(9) —— ZoomButton
查看>>
pcDuino 刷系统-卡刷
查看>>
MySQL结构自动同步工具-schemasync
查看>>
关于在线代码运行网站的一个想法
查看>>
我的友情链接
查看>>
我的友情链接
查看>>
django forms模块使用
查看>>
FreeBSD IPFW 防火墙的安装和设置
查看>>
Linux分区和文件系统 ⑥
查看>>
ClipDrawable--水漫起来的效果
查看>>