一致性HASH

好久没有写文章了,最近忙着公司的事情,也一拖再拖。这篇一致性hash是很久之前就有的一篇算法,记录一下,这周写个基于该算法的Redis中间件。

HASH算法的精髓就在于打散原本杂乱无序的一堆节点,并排序,同时使之首尾相连,形成闭环,总有一个节点是目标节点,最坏情况下是又回到第一个节点

  • 这个算法有性能问题,因为PHP是解释性语言,每次查找一个key都初始化这个环,最好的办法的把这个方法用在daemon进程里,使之缓存起来,就不必每次都执行一次
  1. <?php
  2. namespace WMRedis;
  3. use RedisException;
  4. /**
  5. * 一致性hash
  6. *
  7. * 网上摘抄的一段代码
  8. */
  9. class ConsistenHash
  10. {
  11. /**
  12. * 虚拟节点数
  13. *
  14. * @var int
  15. */
  16. private $_replicas = 64;
  17. /**
  18. * HASH算法对象
  19. * @var object hasher
  20. */
  21. private $_hasher;
  22. /**
  23. * 当前物理节点数
  24. * @var int
  25. */
  26. private $_targetCount = 0;
  27. /**
  28. * 虚拟节点到物理节点映射
  29. * @var array { position => target, ... }
  30. */
  31. private $_positionToTarget = array();
  32. /**
  33. * 物理节点到虚拟节点映射
  34. * @var array { target => [ position, position, ... ], ... }
  35. */
  36. private $_targetToPositions = array();
  37. /**
  38. * 虚拟节点排序标志位
  39. * @var boolean
  40. */
  41. private $_positionToTargetSorted = false;
  42. /**
  43. * 构造函数
  44. * @param object $hasher hasher
  45. * @param int $replicas Amount of positions to hash each target to.
  46. */
  47. public function __construct($hash = 'md5',$replicas = 0)
  48. {
  49. $this->_hasher = strcmp(strtolower($hash),'crc32') === 0 ? new Crc32Hasher() : new Md5Hasher();
  50. $this->_replicas = !$replicas ? $replicas : $this->_replicas;
  51. }
  52. /**
  53. * 添加物理节点
  54. * @param string $target
  55. * @chainable
  56. */
  57. public function addTarget($target)
  58. {
  59. if (isset($this->_targetToPositions[$target]))
  60. {
  61. throw new RedisException("Target '$target' already exists.");
  62. }
  63. $this->_targetToPositions[$target] = array();
  64. // 打散
  65. for ($i = 0; $i < $this->_replicas; $i++)
  66. {
  67. $position = $this->_hasher->hash($target . $i);
  68. $this->_positionToTarget[$position] = $target;
  69. $this->_targetToPositions[$target][]= $position;
  70. }
  71. $this->_positionToTargetSorted = false;
  72. $this->_targetCount++;
  73. return $this;
  74. }
  75. /**
  76. * 批量添加节点
  77. * @param array $targets
  78. * @chainable
  79. */
  80. public function addTargets($targets)
  81. {
  82. foreach ($targets as $target)
  83. {
  84. $this->addTarget($target);
  85. }
  86. return $this;
  87. }
  88. /**
  89. * 删除节点
  90. * @param string $target
  91. * @chainable
  92. */
  93. public function removeTarget($target)
  94. {
  95. if (!isset($this->_targetToPositions[$target]))
  96. {
  97. throw new RedisException("Target '$target' does not exist.");
  98. }
  99. foreach ($this->_targetToPositions[$target] as $position)
  100. {
  101. unset($this->_positionToTarget[$position]);
  102. }
  103. unset($this->_targetToPositions[$target]);
  104. $this->_targetCount--;
  105. return $this;
  106. }
  107. /**
  108. * 返回若有物理节点
  109. * @return array
  110. */
  111. public function getAllTargets()
  112. {
  113. return array_keys($this->_targetToPositions);
  114. }
  115. /**
  116. * 找到资源所在物理节点
  117. * @param string $resource
  118. * @return string
  119. */
  120. public function lookup($resource)
  121. {
  122. $targets = $this->lookupList($resource, 1);
  123. if (empty($targets)) throw new RedisException('No targets exist');
  124. return $targets[0];
  125. }
  126. /**
  127. * 需要多个物理节点
  128. *
  129. * @param string $resource
  130. * @param int $requestedCount 节点个数
  131. * @return array
  132. */
  133. protected function lookupList($resource, $requestedCount)
  134. {
  135. if (!$requestedCount) {
  136. throw new RedisException('Invalid count requested');
  137. }
  138. // 没有节点资源
  139. if (empty($this->_positionToTarget)) {
  140. return array();
  141. }
  142. if ($this->_targetCount == 1) {
  143. return array(array_pop($this->_positionToTarget));
  144. }
  145. $resourcePosition = $this->_hasher->hash($resource);
  146. $results = array();
  147. $collect = false;
  148. $this->_sortPositionTargets();
  149. // 开始搜索
  150. foreach ($this->_positionToTarget as $key => $value)
  151. {
  152. if (!$collect && (string)$key > (string)$resourcePosition)
  153. {
  154. // 找到第一个匹配节点
  155. $collect = true;
  156. }
  157. if ($collect && !in_array($value, $results))
  158. {
  159. $results []= $value;
  160. }
  161. if (count($results) == $requestedCount || count($results) == $this->_targetCount)
  162. {
  163. return $results;
  164. }
  165. }
  166. // 还没有找到足够的节点,则重新开始
  167. foreach ($this->_positionToTarget as $key => $value)
  168. {
  169. if (!in_array($value, $results))
  170. {
  171. $results []= $value;
  172. }
  173. // 已找到足够节点,或所有节点已全部遍历
  174. if (count($results) == $requestedCount || count($results) == $this->_targetCount)
  175. {
  176. return $results;
  177. }
  178. }
  179. // 此时的结果是已遍历完仍然没有足够的节点数
  180. return $results;
  181. }
  182. /**
  183. * 降序排列虚拟节点
  184. */
  185. private function _sortPositionTargets()
  186. {
  187. // sort by key (position) if not already
  188. if (!$this->_positionToTargetSorted)
  189. {
  190. ksort($this->_positionToTarget, SORT_REGULAR);
  191. $this->_positionToTargetSorted = true;
  192. }
  193. }
  194. }
  195. /**
  196. * Crc32
  197. */
  198. class Crc32Hasher implements hasher
  199. {
  200. public function hash($string)
  201. {
  202. return (string)hash('crc32', $string);
  203. }
  204. }
  205. /**
  206. * Md5
  207. */
  208. class Md5Hasher implements hasher
  209. {
  210. public function hash($string)
  211. {
  212. return (string)substr(md5($string), 0, 8);
  213. }
  214. }
  215. /**
  216. * HASH因子接口
  217. */
  218. interface hasher
  219. {
  220. public function hash($string);
  221. }

PHP 一致性Hash的更多相关文章

  1. 对一致性Hash算法,Java代码实现的深入研究

    一致性Hash算法 关于一致性Hash算法,在我之前的博文中已经有多次提到了,MemCache超详细解读一文中"一致性Hash算法"部分,对于为什么要使用一致性Hash算法.一致性 ...

  2. 转载自lanceyan: 一致性hash和solr千万级数据分布式搜索引擎中的应用

    一致性hash和solr千万级数据分布式搜索引擎中的应用 互联网创业中大部分人都是草根创业,这个时候没有强劲的服务器,也没有钱去买很昂贵的海量数据库.在这样严峻的条件下,一批又一批的创业者从创业中获得 ...

  3. 一致性hash算法详解

    转载请说明出处:http://blog.csdn.net/cywosp/article/details/23397179     一致性哈希算法在1997年由麻省理工学院提出的一种分布式哈希(DHT) ...

  4. 探索c#之一致性Hash详解

    阅读目录: 使用场景 算法原理 虚拟节点 代码示例 使用场景 以Redis为例,当系统需要缓存的内容超过单机内存大小时,例如要缓存100G数据,单机内存仅有16G时.这时候就需要考虑进行缓存数据分片, ...

  5. 一致性hash算法简介

    一致性哈希算法在1997年由麻省理工学院提出的一种分布式哈希(DHT)实现算法,设计目标是为了解决因特网中的热点(Hot spot)问题,初衷和CARP十分类似.一致性哈希修正了CARP使用的简单哈希 ...

  6. 分布式缓存技术memcached学习(四)—— 一致性hash算法原理

    分布式一致性hash算法简介 当你看到“分布式一致性hash算法”这个词时,第一时间可能会问,什么是分布式,什么是一致性,hash又是什么.在分析分布式一致性hash算法原理之前,我们先来了解一下这几 ...

  7. 关于Memcached一致性hash的探究

    参考文章 http://blog.chinaunix.net/uid-20498361-id-4303232.html http://blog.csdn.net/kongqz/article/deta ...

  8. 一致性 hash 算法( consistent hashing )a

    一致性 hash 算法( consistent hashing ) 张亮 consistent hashing 算法早在 1997 年就在论文 Consistent hashing and rando ...

  9. Ceph剖析:数据分布之CRUSH算法与一致性Hash

    作者:吴香伟 发表于 2014/09/05 版权声明:可以任意转载,转载时务必以超链接形式标明文章原始出处和作者信息以及版权声明 数据分布是分布式存储系统的一个重要部分,数据分布算法至少要考虑以下三个 ...

  10. 一致性Hash算法

    from wikipedia 一致哈希 历史 1997年由MIT的Karger等在一篇学术论文中提出如何将“一致性Hash”应用于用户易变的分布式Web服务中.也可用于实现健壮缓存来减少大型Web应用 ...

随机推荐

  1. html5-3 html5标签(热点地图如何实现)(边学边做)

    html5-3 html5标签(热点地图如何实现)(边学边做) 一.总结 一句话总结:热点地图用绝对定位实现. 1.自定义列表怎么弄? dl  自定义列表dt  自定义标题dd  自定义列表内容 2. ...

  2. js如何使用正则表达式验证电话号码(可选区号)和邮箱?(分步骤)

    js如何使用正则表达式验证电话号码(可选区号)和邮箱?(分步骤) 一.总结 js进阶正则表达式16电话号码和邮箱正则(分类解决邮箱验证)(分组加?解决电话号码区号选择问题)([\w\.-]中括号解决邮 ...

  3. 【先进的算法】Lasvegas算法3SAT问题(C++实现代码)

    转载请注明出处:http://blog.csdn.net/zhoubin1992/article/details/46469557 1.SAT问题描写叙述 命题逻辑中合取范式 (CNF) 的可满足性问 ...

  4. 小强的HTML5移动开发之路(26)—— JavaScript回顾1

    很久没有怎么用过JavaScript了,感觉有点生疏,最近在看关于HTML5移动开发方面的资料,有一种直觉告诉我,JavaScript昨天.今天很重要,明天会更重要.现在好多基于JavaScript的 ...

  5. C#MVC中创建多模块web应用程序

    当一个应用程序有越来越多的子模块后,应用程序将变得越来越大,复杂度也越来越高,应用程序也越来越难维护.如果把每个子模块,独立分成不同的web应用程序,则这个项目将易于维护.关于这个的好处,我也描述得不 ...

  6. PS 滤镜算法— — 表面模糊

    图像的表面模糊处理,其作用是在保留图像边缘的情况下,对图像的表面进行模糊处理.在对人物皮肤处理上,比高斯模糊更有效.因为高斯模糊在使人物皮肤光洁的同时,也将一些边缘特征如脸部的眉毛.嘴唇等给模糊了,不 ...

  7. Spring boot参考指南

    介绍 转载自:https://www.gitbook.com/book/qbgbook/spring-boot-reference-guide-zh/details 带目录浏览地址:http://ww ...

  8. March 29th, 2015, Thread Name is odd by increasing 1

    public class Fabric extends Thread{ public static void main(String args[]){ Thread t = new Thread(ne ...

  9. 阐述php(五岁以下儿童) 注意事项和使用功能

    1.函数声明 <?php /** * function 函数名(參数1, 參数2.... ){ * 函数体; * 返回值; * } */ $sum = sum(3, 4); echo $sum; ...

  10. 《DELPHI赋》

    <DELPHI赋> -- 武汉NET_TO_DB DELPHI者,经典开发工具.美奂美仑之开发环境也.盖论DELPHI其身世,实为神界之神物,后借宝蓝公司之手,于1990年代,现于江湖. ...