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

相关专题

更多
Golang gRPC 服务开发与Protobuf实战
Golang gRPC 服务开发与Protobuf实战

本专题系统讲解 Golang 在 gRPC 服务开发中的完整实践,涵盖 Protobuf 定义与代码生成、gRPC 服务端与客户端实现、流式 RPC(Unary/Server/Client/Bidirectional)、错误处理、拦截器、中间件以及与 HTTP/REST 的对接方案。通过实际案例,帮助学习者掌握 使用 Go 构建高性能、强类型、可扩展的 RPC 服务体系,适用于微服务与内部系统通信场景。

8

2026.01.15

公务员递补名单公布时间 公务员递补要求
公务员递补名单公布时间 公务员递补要求

公务员递补名单公布时间不固定,通常在面试前,由招录单位(如国家知识产权局、海关等)发布,依据是原入围考生放弃资格,会按笔试成绩从高到低递补,递补考生需按公告要求限时确认并提交材料,及时参加面试/体检等后续环节。要求核心是按招录单位公告及时响应、提交材料(确认书、资格复审材料)并准时参加面试。

44

2026.01.15

公务员调剂条件 2026调剂公告时间
公务员调剂条件 2026调剂公告时间

(一)符合拟调剂职位所要求的资格条件。 (二)公共科目笔试成绩同时达到拟调剂职位和原报考职位的合格分数线,且考试类别相同。 拟调剂职位设置了专业科目笔试条件的,专业科目笔试成绩还须同时达到合格分数线,且考试类别相同。 (三)未进入原报考职位面试人员名单。

58

2026.01.15

国考成绩查询入口 国考分数公布时间2026
国考成绩查询入口 国考分数公布时间2026

笔试成绩查询入口已开通,考生可登录国家公务员局中央机关及其直属机构2026年度考试录用公务员专题网站http://bm.scs.gov.cn/pp/gkweb/core/web/ui/business/examResult/written_result.html,查询笔试成绩和合格分数线,点击“笔试成绩查询”按钮,凭借身份证及准考证进行查询。

11

2026.01.15

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

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

65

2026.01.14

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

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

36

2026.01.13

PHP 高性能
PHP 高性能

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

75

2026.01.13

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

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

21

2026.01.13

PHP 文件上传
PHP 文件上传

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

35

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号