0

0

一致性hash - php

php中文网

php中文网

发布时间:2016-07-29 09:11:20

|

1017人浏览过

|

来源于php中文网

原创

/**
 * flexihash - a simple consistent hashing implementation for php.
 * 
 * the mit license
 * 
 * copyright (c) 2008 paul annesley
 * 
 * permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "software"), to deal
 * in the software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the software, and to permit persons to whom the software is
 * furnished to do so, subject to the following conditions:
 * 
 * the above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the software.
 * 
 * the software is provided "as is", without warranty of any kind, express or
 * implied, including but not limited to the warranties of merchantability,
 * fitness for a particular purpose and noninfringement. in no event shall the
 * authors or copyright holders be liable for any claim, damages or other
 * liability, whether in an action of contract, tort or otherwise, arising from,
 * out of or in connection with the software or the use or other dealings in
 * the software.
 * 
 * @author paul annesley
 * @link http://paul.annesley.cc/
 * @copyright paul annesley, 2008
 * @comment by myz (http://blog.csdn.net/mayongzhan)
 */
/**
 * a simple consistent hashing implementation with pluggable hash algorithms.
 *
 * @author paul annesley
 * @package flexihash
 * @licence http://www.opensource.org/licenses/mit-license.php
 */
class flexihash
{
/**
* the number of positions to hash each target to.
*
* @var int
* @comment 虚拟节点数,解决节点分布不均的问题
*/
private $_replicas = 64;
/**
* the hash algorithm, encapsulated in a flexihash_hasher implementation.
* @var object flexihash_hasher
* @comment 使用的hash方法 : md5,crc32
*/
private $_hasher;
/**
* internal counter for current number of targets.
* @var int
* @comment 节点记数器
*/
private $_targetcount = 0;
/**
* internal map of positions (hash outputs) to targets
* @var array { position => target, ... }
* @comment 位置对应节点,用于lookup中根据位置确定要访问的节点
*/
private $_positiontotarget = array();
/**
* internal map of targets to lists of positions that target is hashed to.
* @var array { target => [ position, position, ... ], ... }
* @comment 节点对应位置,用于删除节点
*/
private $_targettopositions = array();
/**
* whether the internal map of positions to targets is already sorted.
* @var boolean
* @comment 是否已排序
*/
private $_positiontotargetsorted = false;
/**
* constructor
* @param object $hasher flexihash_hasher
* @param int $replicas amount of positions to hash each target to.
* @comment 构造函数,确定要使用的hash方法和需拟节点数,虚拟节点数越多,分布越均匀,但程序的分布式运算越慢
*/
public function __construct(flexihash_hasher $hasher = null, $replicas = null)
{
$this->_hasher = $hasher ? $hasher : new flexihash_crc32hasher();
if (!empty($replicas)) $this->_replicas = $replicas;
}
/**
* add a target.
* @param string $target
* @chainable
* @comment 添加节点,根据虚拟节点数,将节点分布到多个虚拟位置上
*/
public function addtarget($target)
{
if (isset($this->_targettopositions[$target]))
{
throw new flexihash_exception("target '$target' already exists.");
}
$this->_targettopositions[$target] = array();
// hash the target into multiple positions
for ($i = 0; $i _replicas; $i++)
{
$position = $this->_hasher->hash($target . $i);
$this->_positiontotarget[$position] = $target; // lookup
$this->_targettopositions[$target] []= $position; // target removal
}
$this->_positiontotargetsorted = false;
$this->_targetcount++;
return $this;
}
/**
* add a list of targets.
* @param array $targets
* @chainable
*/
public function addtargets($targets)
{
foreach ($targets as $target)
{
$this->addtarget($target);
}
return $this;
}
/**
* remove a target.
* @param string $target
* @chainable
*/
public function removetarget($target)
{
if (!isset($this->_targettopositions[$target]))
{
throw new flexihash_exception("target '$target' does not exist.");
}
foreach ($this->_targettopositions[$target] as $position)
{
unset($this->_positiontotarget[$position]);
}
unset($this->_targettopositions[$target]);
$this->_targetcount--;
return $this;
}
/**
* a list of all potential targets
* @return array
*/
public function getalltargets()
{
return array_keys($this->_targettopositions);
}
/**
* looks up the target for the given resource.
* @param string $resource
* @return string
*/
public function lookup($resource)
{
$targets = $this->lookuplist($resource, 1);
if (empty($targets)) throw new flexihash_exception('no targets exist');
return $targets[0];
}
/**
* get a list of targets for the resource, in order of precedence.
* up to $requestedcount targets are returned, less if there are fewer in total.
*
* @param string $resource
* @param int $requestedcount the length of the list to return
* @return array list of targets
* @comment 查找当前的资源对应的节点,
*          节点为空则返回空,节点只有一个则返回该节点,
*          对当前资源进行hash,对所有的位置进行排序,在有序的位置列上寻找当前资源的位置
*          当全部没有找到的时候,将资源的位置确定为有序位置的第一个(形成一个环)
*          返回所找到的节点
*/
public function lookuplist($resource, $requestedcount)
{
if (!$requestedcount)
throw new flexihash_exception('invalid count requested');
// handle no targets
if (empty($this->_positiontotarget))
return array();
// optimize single target
if ($this->_targetcount == 1)
return array_unique(array_values($this->_positiontotarget));
// hash resource to a position
$resourceposition = $this->_hasher->hash($resource);
$results = array();
$collect = false;
$this->_sortpositiontargets();
// search values above the resourceposition
foreach ($this->_positiontotarget as $key => $value)
{
// start collecting targets after passing resource position
if (!$collect && $key > $resourceposition)
{
$collect = true;
}
// only collect the first instance of any target
if ($collect && !in_array($value, $results))
{
$results []= $value;
}
// return when enough results, or list exhausted
if (count($results) == $requestedcount || count($results) == $this->_targetcount)
{
return $results;
}
}
// loop to start - search values below the resourceposition
foreach ($this->_positiontotarget as $key => $value)
{
if (!in_array($value, $results))
{
$results []= $value;
}
// return when enough results, or list exhausted
if (count($results) == $requestedcount || count($results) == $this->_targetcount)
{
return $results;
}
}
// return results after iterating through both "parts"
return $results;
}
public function __tostring()
{
return sprintf(
'%s{targets:[%s]}',
get_class($this),
implode(',', $this->getalltargets())
);
}
// ----------------------------------------
// private methods
/**
* sorts the internal mapping (positions to targets) by position
*/
private function _sortpositiontargets()
{
// sort by key (position) if not already
if (!$this->_positiontotargetsorted)
{
ksort($this->_positiontotarget, sort_regular);
$this->_positiontotargetsorted = true;
}
}
}
/**
 * hashes given values into a sortable fixed size address space.
 *
 * @author paul annesley
 * @package flexihash
 * @licence http://www.opensource.org/licenses/mit-license.php
 */
interface flexihash_hasher
{
/**
* hashes the given string into a 32bit address space.
*
* note that the output may be more than 32bits of raw data, for example
* hexidecimal characters representing a 32bit value.
*
* the data must have 0xffffffff possible values, and be sortable by
* php sort functions using sort_regular.
*
* @param string
* @return mixed a sortable format with 0xffffffff possible values
*/
public function hash($string);
}
/**
 * uses crc32 to hash a value into a signed 32bit int address space.
 * under 32bit php this (safely) overflows into negatives ints.
 *
 * @author paul annesley
 * @package flexihash
 * @licence http://www.opensource.org/licenses/mit-license.php
 */
class flexihash_crc32hasher
implements flexihash_hasher
{
/* (non-phpdoc)
* @see flexihash_hasher::hash()
*/
public function hash($string)
{
return crc32($string);
}
}
/**
 * uses crc32 to hash a value into a 32bit binary string data address space.
 *
 * @author paul annesley
 * @package flexihash
 * @licence http://www.opensource.org/licenses/mit-license.php
 */
class flexihash_md5hasher
implements flexihash_hasher
{
/* (non-phpdoc)
* @see flexihash_hasher::hash()
*/
public function hash($string)
{
return substr(md5($string), 0, 8); // 8 hexits = 32bit
// 4 bytes of binary md5 data could also be used, but
// performance seems to be the same.
}
}
/**
 * an exception thrown by flexihash.
 *
 * @author paul annesley
 * @package flexihash
 * @licence http://www.opensource.org/licenses/mit-license.php
 */
class flexihash_exception extends exception
{
}

以上就介绍了一致性hash - php,包括了Exception方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

相关文章

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

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

下载

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

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
batoto漫画官网入口与网页版访问指南
batoto漫画官网入口与网页版访问指南

本专题系统整理batoto漫画官方网站最新可用入口,涵盖最新官网地址、网页版登录页面及防走失访问方式说明,帮助用户快速找到batoto漫画官方平台,稳定在线阅读各类漫画内容。

331

2026.02.25

Steam官网正版入口与注册登录指南_新手快速进入游戏平台方法
Steam官网正版入口与注册登录指南_新手快速进入游戏平台方法

本专题系统整理Steam官网最新可用入口,涵盖网页版登录地址、新用户注册流程、账号登录方法及官方游戏商店访问说明,帮助新手玩家快速进入Steam平台,完成注册登录并管理个人游戏库。

49

2026.02.25

TypeScript全栈项目架构与接口规范设计
TypeScript全栈项目架构与接口规范设计

本专题面向全栈开发者,系统讲解基于 TypeScript 构建前后端统一技术栈的工程化实践。内容涵盖项目分层设计、接口协议规范、类型共享机制、错误码体系设计、接口自动化生成与文档维护方案。通过完整项目示例,帮助开发者构建结构清晰、类型安全、易维护的现代全栈应用架构。

33

2026.02.25

Python数据处理流水线与ETL工程实战
Python数据处理流水线与ETL工程实战

本专题聚焦 Python 在数据工程场景下的实际应用,系统讲解 ETL 流程设计、数据抽取与清洗、批处理与增量处理方案,以及数据质量校验与异常处理机制。通过构建完整的数据处理流水线案例,帮助开发者掌握数据工程中的性能优化思路与工程化规范,为后续数据分析与机器学习提供稳定可靠的数据基础。

13

2026.02.25

Java领域驱动设计(DDD)与复杂业务建模实战
Java领域驱动设计(DDD)与复杂业务建模实战

本专题围绕 Java 在复杂业务系统中的建模与架构设计展开,深入讲解领域驱动设计(DDD)的核心思想与落地实践。内容涵盖领域划分、聚合根设计、限界上下文、领域事件、贫血模型与充血模型对比,并结合实际业务案例,讲解如何在 Spring 体系中实现可演进的领域模型架构,帮助开发者应对复杂业务带来的系统演化挑战。

5

2026.02.25

Golang 生态工具与框架:扩展开发能力
Golang 生态工具与框架:扩展开发能力

《Golang 生态工具与框架》系统梳理 Go 语言在实际工程中的主流工具链与框架选型思路,涵盖 Web 框架、RPC 通信、依赖管理、测试工具、代码生成与项目结构设计等内容。通过真实项目场景解析不同工具的适用边界与组合方式,帮助开发者构建高效、可维护的 Go 工程体系,并提升团队协作与交付效率。

19

2026.02.24

Golang 性能优化专题:提升应用效率
Golang 性能优化专题:提升应用效率

《Golang 性能优化专题》聚焦 Go 应用在高并发与大规模服务中的性能问题,从 profiling、内存分配、Goroutine 调度、GC 机制到 I/O 与锁竞争逐层分析。结合真实案例讲解定位瓶颈的方法与优化策略,帮助开发者建立系统化性能调优思维,在保证代码可维护性的同时显著提升服务吞吐与稳定性。

9

2026.02.24

Golang 面试题精选:高频问题与解答
Golang 面试题精选:高频问题与解答

Golang 面试题精选》系统整理企业常见 Go 技术面试问题,覆盖语言基础、并发模型、内存与调度机制、网络编程、工程实践与性能优化等核心知识点。每道题不仅给出答案,还拆解背后的设计原理与考察思路,帮助读者建立完整知识结构,在面试与实际开发中都能更从容应对复杂问题。

7

2026.02.24

Golang 运行与部署实战:从本地到云端
Golang 运行与部署实战:从本地到云端

《Golang 运行与部署实战》围绕 Go 应用从开发完成到稳定上线的完整流程展开,系统讲解编译构建、环境配置、日志与配置管理、容器化部署以及常见运维问题处理。结合真实项目场景,拆解自动化构建与持续部署思路,帮助开发者建立可靠的发布流程,提升服务稳定性与可维护性。

5

2026.02.24

热门下载

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

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
JavaScript高级框架设计视频教程
JavaScript高级框架设计视频教程

共22课时 | 3.6万人学习

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

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