PHP实现的服务器一致性hash分布算法示例
发布:smiling 来源: PHP粉丝网 添加日期:2021-10-23 14:25:08 浏览: 评论:0
这篇文章主要介绍了PHP实现的服务器一致性hash分布算法,结合实例形式分析了php一致性hash分布算法类的具体定义与相关使用技巧,需要的朋友可以参考下。
本文实例讲述了PHP实现的服务器一致性hash分布算法,分享给大家供大家参考,具体如下:
- <?php
- /**
- * 对服务器进行一致性hash分布算法
- */
- class HashRing
- {
- private $servers = array();
- private $nodeList = array();
- private $nodeHashList = array();
- private $nodeTotalNum = 0;
- private $virtualNodeNum = 32;
- private $keyHash = '';
- public function __construct($servers)
- {
- $this->servers = $servers;
- foreach ($servers as $server) {
- for ($i = 0; $i < $this->virtualNodeNum; $i++) {
- $this->nodeList[sprintf("%u", crc32($server.'-'.$i))] = array($server, $i);
- }
- }
- ksort($this->nodeList);
- $this->nodeHashList = array_keys($this->nodeList);
- }
- private function getNodeIndex($key)
- {
- $this->keyHash = sprintf("%u", crc32($key));
- if ($this->keyHash > end($this->nodeHashList)) {
- $this->keyHash = $this->keyHash % end($this->nodeHashList);
- }
- if ($this->keyHash <= reset($this->nodeHashList)) {
- return 0;
- }
- $this->nodeTotalNum = count($this->nodeHashList);
- return $this->binaryChopIndex(0, $this->nodeTotalNum);
- }
- private function binaryChopIndex($l=0, $r=0)
- {
- if ($l < $r) {
- $avg = intval(($l+$r) / 2);
- if ($this->nodeHashList[$avg] == $this->keyHash) {
- return $avg;
- } elseif ($this->keyHash < $this->nodeHashList[$avg] && ($avg > 0)) {
- return $this->binaryChopIndex($l, $avg-1);
- } else {
- return $this->binaryChopIndex($avg+1, $r);
- }
- } else {
- return $l;
- }
- }
- public function getServersByKey($key, $num=1)
- {
- $index = $this->getNodeIndex($key);
- $server = $this->nodeList[$this->nodeHashList[$index]];
- if ($num == 1) {
- return $server[0];
- }
- if ($num >= count($this->servers)) {
- $num = count($this->servers);
- }
- $result = array($server[0]);
- for ($i=$index+1; true; $i++) {
- if ($i >= $this->nodeTotalNum) {
- $i = 0;
- }
- $nextServer = $this->nodeList[$this->nodeHashList[$i]];
- if (!in_array($nextServer[0], $result)) {
- $result[] = $nextServer[0];
- }
- if (count($result) == $num) {
- break;
- }
- }
- return $result;
- }
- }
- //示例
- $servers = array(
- '127.0.0.1:11211',
- '127.0.0.1:11212',
- '127.0.0.1:11213',
- '127.0.0.1:11214',
- '127.0.0.1:11215'
- );
- $obj = new HashRing($servers);
- $servers = $obj->getServersByKey('testkey', 2);
- print_r($servers);
- echo "\n";
运行结果:
- Array
- (
- [0] => 127.0.0.1:11214
- [1] => 127.0.0.1:11211
- )
Tags: PHP服务器一致性 hash分布
相关文章
- ·PHP一致性hash分布式算法封装类定义与用法示例(2021-10-22)
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)