0

0

PHPhash一致性

PHP中文网

PHP中文网

发布时间:2016-05-22 17:22:20

|

1213人浏览过

|

来源于php中文网

原创

        跳至                   

_hasher = $hasher?$hasher: new FlexiHash_Crc32Hasher();
		// 虚拟节点的个数
		if (!empty($replicas)){
			$this->_replicas = $replicas;
		}
	}
	
	/**
	 * 增加节点,根据虚拟节点数,把节点分布到更多的虚拟位置上
	 */
	public function addTarget($target){
		
		if (isset($this->_targetToPositions[$target])) {
			throw new FlexiHash_Exception("Target $target already exists.");
		}
		
		$this->_targetToPositions[$target] = array();
		
		for ($i = 0; $i < $this->_replicas; $i++) {
			
			// 根据规定的方法hash
			$position = $this->_hasher->hash($target.$i);
			
			// 虚拟节点对应的真实的节点
			$this->_positionToTarget[$position] = $target;
			
			// 真实节点包含的虚拟节点
			$this->_targetToPositions[$target][] = $position;
		}
		
		
		$this->_positionToTargetSorted = false;
		
		// 真实节点个数
		$this->_targetCount++;
		
		return $this;
	}
	
	/**
	 * 添加多个节点
	 * 
	 */
	public function addTargets($targets){
		foreach ($targets as $target){
			$this->addTarget($target);
		}
		return $this;
	}
	
	/**
	 * 移除某个节点
	 * 
	 */
	public function removeTarget($target){
		if (!isset($this->_targetToPositions[$target])){
			throw new FlexiHash_Exception("target $target does not exist\n");
		}
		
		foreach($this->_targetToPositions[$target] as $position){
			unset($this->_positionToTarget[$position]);
		}
		
		unset($this->_targetToPositions[$target]);
		
		$this->_targetCount--;
		
		return $this;
	}
	
	/**
	 * 获取所有节点
	 * 
	 */
	public function getAllTargets(){
		return array_keys($this->_targetToPositions);
	}
	
	
	/**
	 * 根据key查找hash到的真实节点
	 * 
	 */
	public function lookup($resource){
		$targets = $this->lookupList($resource, 1);
		
		if (empty($targets)){
			throw new FlexiHash_Exception("no targets exist");
		}
		
		return $targets[0];
	}
	
	/**
	 * 查找资源存在的节点
	 * 
	 * 描述:根据要求的数量,返回与$resource哈希后数值相等或比其大并且是最小的数值对应的节点,若不存在或数量不够,则从虚拟节点排序后的前一个或多个
	 */
	public function lookupList($resource, $requestedCount){
		
		if (!$requestedCount) {
			throw new FlexiHash_Exception('Invalid count requested');
		}
		
		if (empty($this->_positionToTarget)) {
			return array();
		}
		
		// 直接节点只有一个的时候
		if ($this->_targetCount == 1 ){
			return array_unique(array_values($this->_positionToTarget));
		}
		
		// 获取当前key进行hash后的值
		$resourcePosition = $this->_hasher->hash($resource);
	
		$results = array();
		
		$collect = false;
		
		$this->_sortPositionTargets();
		
		// 查找与$resourcePosition 相等或比其大并且是最小的数
		foreach($this->_positionToTarget as $key => $value){
			
			if (!$collect && $key > $resourcePosition){
				
				$collect = true;
			}
			
			if ($collect && !in_array($value, $results)){
				$results[] = $value;
			}
			
			// 找到$requestedCount 或个数与真实节点数量相同
			if (count($results) == $requestedCount || count($results) == $this->_targetCount){
				return $results;
			}
		}
		// 如数量不够或者未查到,则从第一个开始,将$results中不存在前$requestedCount-count($results),设置为需要的节点
		foreach ($this->_positionToTarget as $key => $value){
			if (!in_array($value, $results)){
				$results[] = $value;
			}
			
			if (count($results) == $requestedCount || count($results) == $this->_targetCount){
			
				return $results;
			}
		}
		
		return $results;
		
	}
	
	/**
	 * 根据虚拟节点进行排序
	 */
	private function _sortPositionTargets(){
		if (!$this->_positionToTargetSorted){
			ksort($this->_positionToTarget, SORT_REGULAR);
			
			$this->_positionToTargetSorted = true;
		}
	}
	
}// end class

/**
 * hash方式
 */
interface FlexiHash_Hasher{
	public function hash($string);
}

class FlexiHash_Crc32Hasher implements FlexiHash_Hasher{
	public function hash($string){
		return sprintf("%u",crc32($string));
	}
}


class FlexiHash_Md5Hasher implements FlexiHash_Hasher{
	public function hash($string){
		return substr(md5($string), 0, 8);
	}
}

class FlexiHash_Exception extends Exception{
}

$runData['BEGIN_TIME'] = microtime(true);

for($i=0;$iaddTargets($targetsArray);
	  $key = md5(mt_rand());
	 $targets = $flexiHashObj->lookup($key);
//	var_dump($targets);
	 
	 

}
	echo "一致性hash:";
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));




$runData['BEGIN_TIME'] = microtime(true); 
$m= new Memcache;
$m->connect('127.0.0.1', 11211); 
for($i=0;$iset($key, time(), 0, 10);
}
echo "单台机器:";
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));
?>

                                       

           

2. [代码]虚拟节点的hash一致性     

$value){  
              
            for ($i = 0; $i < $this->_virtualNodeNum; $i++){  
                $this->_node[sprintf("%u", crc32($value."#".$i))] = $value."#".$i;  
            }  
        }  
          
        // 排序  
        ksort($this->_node);  
          
//      print_r($this->_node);  
    }  
      
    // 单例模式  
    static public function getInstance(){  
        static $memcacheObj = null;  
        if (!is_object($memcacheObj)) {  
            $memcacheObj = new self();  
        }  
        return $memcacheObj;  
    }  
      
    private function _connectMemcache($key){  
        $this->_nodeData = array_keys($this->_node);  
//      echo "all node:\n";  
//      print_r($this->_nodeData);  
        $this->_keyNode = sprintf("%u", crc32($key));  
//      $this->_keyNode = 1803717635;  
//      var_dump($this->_keyNode);  
          
        // 获取key值对应的最近的节点  
        $nodeKey = $this->_findServerNode(0, count($this->_nodeData)-1);  
//      var_dump($nodeKey);  
//      echo "$this->_keyNode :search node:$nodeKey  IP:{$this->_node[$nodeKey]}\n";  
          
        //获取对应的真实ip  
        list($config, $num) = explode("#", $this->_node[$nodeKey]);  
          
        if (empty($config)){  
            throw new Exception("serach ip config error");  
        }  
          
        if (!isset($this->_memcache[$config])){  
            $this->_memcache[$config] = new Memcache;  
            list($host, $port) = explode(":", $config);  
            $this->_memcache[$config]->connect($host, $port);  
        }  
          
        return $this->_memcache[$config];  
          
          
          
    }  
    /** 
     * 采用二分法从虚拟memcache节点中查找最近的节点 
     * @param int $low 开始位置 
     * @param int $high 结束位置 
     *  
     */  
    private function _findServerNode($low, $high){  
          
        // 开始下标小于结束下标  
        if ($low < $high){  
              
            $avg = intval(($low+$high)/2);  
              
            if ($this->_nodeData[$avg] == $this->_keyNode){  
                return $this->_nodeData[$avg];  
            }elseif ($this->_keyNode < $this->_nodeData[$avg]){  
                return $this->_findServerNode($low, $avg-1);  
            }else{  
                return $this->_findServerNode($avg+1, $high);  
            }  
        }else if(($low == $high)){  
            // 大于平均值  
            if ($low ==0 || $low == count($this->_nodeData)-1){  
                return $this->_nodeData[$low];  
            }  
//          var_dump($low);  
            if ($this->_nodeData[$low] < $this->_keyNode){  
                  
                if (abs($this->_nodeData[$low] - $this->_keyNode) < abs($this->_nodeData[$low+1]-$this->_keyNode)){  
                    return $this->_nodeData[$low];  
                }else{  
                    return $this->_nodeData[$low+1];  
                }  
          
            }else {  
                if (abs($this->_nodeData[$low] - $this->_keyNode) < abs($this->_nodeData[$low-1]-$this->_keyNode)){  
                    return $this->_nodeData[$low];  
                }else{  
                    return $this->_nodeData[$low-1];  
                }  
            }  
        }else{  
            if ( ($low == 0)&&($high < 0) ){  
                return $this->_nodeData[$low];  
            }  
          
            if (abs($this->_nodeData[$low] - $this->_keyNode) < abs($this->_nodeData[$high]-$this->_keyNode)){  
                return $this->_nodeData[$low];  
            }else{  
                return $this->_nodeData[$high];  
            }  
        }  
    }  
      
    public function set($key, $value, $expire=0){  
//  var_dump($key);  
        return $this->_connectMemcache($key)->set($key, json_encode($value), 0, $expire);  
    }  
      
      
    public function add($key, $vakue, $expire=0){  
        return $this->_connectMemcache($key)->add($key, json_encode($value), 0, $expire);  
    }  
      
    public function get($key){  
        return $this->_connectMemcache($key)->get($key, true);  
    }  
      
    public function delete($key){  
        return $this->_connectMemcache($key)->delete($key);  
    }  
      
          
      
}  
  
  
$runData['BEGIN_TIME'] = microtime(true);  
//测试一万次set加get  
for($i=0;$iset($key, time(), 10);  
}  
echo "一致性hash:";  
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));  
$runData['BEGIN_TIME'] = microtime(true);   
$m= new Memcache;  
$m->connect('127.0.0.1', 11211);   
for($i=0;$iset($key, time(), 0, 10);  
}  
echo "单台机器:";  
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));

           

OneStory
OneStory

OneStory 是一款创新的AI故事生成助手,用AI快速生成连续性、一致性的角色和故事。

下载

       

立即学习PHP免费学习笔记(深入)”;

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Java 桌面应用开发(JavaFX 实战)
Java 桌面应用开发(JavaFX 实战)

本专题系统讲解 Java 在桌面应用开发领域的实战应用,重点围绕 JavaFX 框架,涵盖界面布局、控件使用、事件处理、FXML、样式美化(CSS)、多线程与UI响应优化,以及桌面应用的打包与发布。通过完整示例项目,帮助学习者掌握 使用 Java 构建现代化、跨平台桌面应用程序的核心能力。

63

2026.01.14

php与html混编教程大全
php与html混编教程大全

本专题整合了php和html混编相关教程,阅读专题下面的文章了解更多详细内容。

31

2026.01.13

PHP 高性能
PHP 高性能

本专题整合了PHP高性能相关教程大全,阅读专题下面的文章了解更多详细内容。

73

2026.01.13

MySQL数据库报错常见问题及解决方法大全
MySQL数据库报错常见问题及解决方法大全

本专题整合了MySQL数据库报错常见问题及解决方法,阅读专题下面的文章了解更多详细内容。

20

2026.01.13

PHP 文件上传
PHP 文件上传

本专题整合了PHP实现文件上传相关教程,阅读专题下面的文章了解更多详细内容。

24

2026.01.13

PHP缓存策略教程大全
PHP缓存策略教程大全

本专题整合了PHP缓存相关教程,阅读专题下面的文章了解更多详细内容。

7

2026.01.13

jQuery 正则表达式相关教程
jQuery 正则表达式相关教程

本专题整合了jQuery正则表达式相关教程大全,阅读专题下面的文章了解更多详细内容。

4

2026.01.13

交互式图表和动态图表教程汇总
交互式图表和动态图表教程汇总

本专题整合了交互式图表和动态图表的相关内容,阅读专题下面的文章了解更多详细内容。

49

2026.01.13

nginx配置文件详细教程
nginx配置文件详细教程

本专题整合了nginx配置文件相关教程详细汇总,阅读专题下面的文章了解更多详细内容。

11

2026.01.13

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PostgreSQL 教程
PostgreSQL 教程

共48课时 | 7.2万人学习

Django 教程
Django 教程

共28课时 | 3.1万人学习

NumPy 教程
NumPy 教程

共44课时 | 2.9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号