一致性哈希算法PHP测试片段
<?php
header('Content-type: text/html; charset=utf8');
# 抽象接口
interface hash{
public function _hash($str);
}
interface distribution{
public function lookup($key);
}
# hash 算法实例
class Consistent implements hash,distribution {
protected $point_num = 64;
protected $posi = array();
protected $server;
#计算一个hash值
public function _hash($str){
return sprintf('%u',crc32($str));
}
# 计算key分布到的服务器
public function lookup($key){
foreach($this->posi as $k=>$v){
if ($this->_hash($key) <= $k ){
$this->server = $v;
break;
}
}
return $this->server;
}
# 添加服务节点
public function addServer($server){
for ($i=1;$i<=$this->point_num;$i++){
$this->posi[$this->_hash($server.'_'.$i)] = $server;
}
$this->sortPosi();
}
#排序定位点
public function sortPosi(){
ksort($this->posi);
}
#打印定位点
public function printPosi(){
echo '<pre>';
print_r($this->posi);
}
}
$hash = new Consistent();
$hash->addServer('a');
$hash->addServer('b');
$hash->addServer('c');
#test hash
$key = 'abc';
$server = $hash->lookup($key);
echo $key.'对应的服务器是:'.$Server.' 对应的hash值是:'.$hash->_hash($key);
echo '<hr />';
$hash->printPosi();
最新文章
- 解决jquery1.9不支持browser对象的问题||TypeError: $.browser is undefined
- PHP 增删改查
- 【CTO讲堂】以API为核心的移动应用云大发展时代
- android开发环境搭建(64位)
- C#根据当前日期获取星期和阴历日期
- 如何定制Sink扩展.Net Remoting功能
- Supervisor的安装与使用入门
- javascript高级特性(面向对象)
- 有关JAVA基础学习中的集合讨论
- poj 2155 Matrix (二维树状数组)
- 前馈神经网络-反向传播(Back Propagation)公式推导走读
- Uva - 230 - Borrowers
- Extjs6 grid 导出excel功能类,支持renderer
- 【Java8】@FunctionalInterface
- Educational Codeforces Round 53 (Rated for Div. 2)
- 除了Office和wps,还有什么办公软件比较好用?
- shell脚本之使用sed和awk进行文本处理
- HTML 表单中的验证
- 【Web】前端裁剪图片,并上传到服务器(Jcrop+canvas)
- 在运行bat文件时,报错发生系统错误123,文件名,目录名或卷标语法不正确