<?php
/**
*@author:xiaojiang 20140222
* 一致性哈希php 实现
*/ class MyHash{ //虚拟节点数
private $_virtualCounts = 2;
//虚拟节点集合
private $_circleItems = array();
//实际节点
private $_items = array();
//实际节点数
private $_itemsCount = 0;
//是否需要排序
private $_itemRelKey = array();
private $needSort = false; private $algo; public function __construct( hash_algo $algo = null ){
if( !$algo ){
$this->algo = new algo_md5();
}
} public function addItem( $_item ){ if( isset( $this->_items[$_item]) ){
throw new Exception("item exists");
}
$this->_items[$_item] = array();
for( $i = 0; $i < $this->_virtualCounts; $i++ ){
$_virturalKey = $this->algo->run( $_item.$i );
$this->_circleItems[$_virturalKey] = $_item;
$this->_itemRelKey[$_item][] = $_virturalKey;
}
$this->needSort = true;
$this->_itemsCount++;
} public function removeItem( $_item ){ if( !isset( $this->_items[$_item] ) ){
throw new Exception("item is not exists");
}
foreach( $this->_itemRelKey[$_item] as $key){
unset( $this->_circleItems[$key] );
}
unset($this->_items[$_item]);
$this->_itemsCount--;
} public function getKey( $str ){ if($this->needSort){
$this->sortItems();
} $_sk = $this->algo->run( $str );
echo $_sk;
foreach( $this->_circleItems as $key => $_item){ if( $key > $_sk ){
return $_item;
}
}
$ret = array_values(array_slice($this->_circleItems , 0 ,1));
return $ret[0]; } private function sortItems(){ ksort( $this->_circleItems ,SORT_STRING );
$this->needSort = false;
} public function _t(){
print_r($this->_circleItems);
}
}
Interface hash_algo{
function run();
}
class algo_md5{
function run( $_str ){
return MD5( $_str );
}
}
$_tstr = "B8aaaaa";
$thash = new MyHash();
$thash->addItem("10.100.200.3");
$thash->addItem("10.100.200.4"); //$a = $thash->getKey($_tstr);
//$thash->_t(); $thash->removeItem("10.100.200.4");
$thash->_t(); ?>

主要解决多服务器的分布式选择问题。。 提高中间层服务器的部署灵活性

最新文章

  1. 永远不要修改arguments对象
  2. string用法
  3. struts2&amp;&amp;Hibernate Demo1
  4. css 细节收集
  5. eclipse jdk配置
  6. CloudSTack4.2 查看所有虚拟机API测试
  7. Largest product in a series
  8. 苹果新的编程语言 Swift 语言进阶(六)--函数和闭包
  9. puppet的配置清单书写
  10. 【js编程艺术】小制作五
  11. (转)cacti无图无数据等常见问题排查
  12. 暑假练习赛 004 E Joint Stacks(优先队列模拟)
  13. VMware 设置共享目录
  14. Swoft 缓存及Redis使用
  15. List和符号分隔的字符串互相转换
  16. 使用binlog,实现MySQL数据恢复
  17. 深入理解C++中public、protected及private用法
  18. EF简易教程,从建表到表间关系
  19. 安装配置maven私服-nexus
  20. ASP.NET的页面执行过程

热门文章

  1. Mac 下 Homebrew(类似CentOS下的yum)简介及安装
  2. Spring JDBC SimpleJdbcCall类示例
  3. (转)谈谈RTP传输中的负载类型和时间戳
  4. html固定宽度下拉框内容显示不全问题解决方法
  5. C# 指定ip段生成ip地址
  6. MySql:charset和collation的设置
  7. C#网络编程之Http请求
  8. 8 云计算系列之Horizon的安装与虚拟机创建流程
  9. yield 举例
  10. Ubuntu中的“资源管理器”System Monitor