- 浏览: 25142 次
- 性别:
- 来自: 深圳
-
文章分类
最新评论
代码转载:http://txf2004.iteye.com/blog/612507 作者:txf2004 标题:一致性哈希
主要实现了一致性哈希的算法,php界相当优秀的代码。谢谢txf2004。
主要实现了一致性哈希的算法,php界相当优秀的代码。谢谢txf2004。
<?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 < $this->_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 { }
发表评论
-
HandlerSocket安装测试
2012-02-08 14:41 958目前使用MySQL的网站, ... -
nodejs教程
2012-02-07 14:03 835http://club.cnodejs.org/tag/%E5 ... -
jQuery学习: 实现select multiple左右添加和删除功能
2012-02-07 11:01 764项目要实现这样 的一个功能(如下图所示):选择左边下拉列 ... -
mysql
2012-01-19 11:06 545http://wenku.baidu.com/view/aa4 ... -
PHP开发者常犯的10个MySQL错误
2012-01-18 00:05 555来源:http://cnbeta.com/articles/1 ... -
你在用什么字体编程
2011-11-16 00:13 774编写程序时,对字 ... -
cakephp使用事务
2011-11-08 19:20 1350begin;INSERT INTO `dev_dgc`.`us ... -
php 得到上周,本周,上月,本月,本季度,上季度
2011-11-07 14:17 887出处:http://hudeyong926.ite ... -
抄摘:我为什么选择MongoDB(用于备忘)
2011-10-27 23:33 559抄摘:我为什么选择Mong ... -
php __call and __callStatic
2011-10-20 10:22 990PHP5 的对象新增了一个专用方法 __call(),这个方法 ... -
使用Cacti监控MongoDB和Redis
2011-10-19 10:10 1285原文地址:http://blog.nosqlfan.com/h ... -
php 获取 POST JSON 数据
2011-10-17 13:39 3304在通过ajax向php程序中传递数据时,会发现使用$_POST ...
相关推荐
一个用于在客户端使用一致性哈希连接 redis 服务器或者 redis 节点集群的 scala 库。Redis Scala 客户端图书馆的主要特色本机 Scala 类型设置和列表响应。在客户端上保持一致的哈希值。支持Redis节点集群。关于 ...
一致性哈希算法是在分布式系统中广泛使用的一种数据定位算法,尤其适用于分布式缓存系统,如Redis。传统的哈希算法在分布式存储系统中有一个缺点,即当系统扩展或缩减节点时,数据的迁移量过大。一致性哈希算法通过...
- **使用tomcat-redis-session-manager**: `tomcat-redis-session-manager-1.2-tomcat-7-java-7.jar`是专门用于整合Tomcat和Redis的Session管理器。同样将其放入Tomcat的`lib`目录。 - **配置Tomcat**:修改`conf/...
为了整合Redis和Tomcat,我们需要解决的主要问题是如何将session数据存储到Redis中,以实现session的共享和持久化。这里的关键在于使用一个名为"Session Manager"的组件,它负责在用户session创建、更新和销毁时与...
一致性哈希算法是一种在分布式系统中用于解决数据分发和负载均衡问题的算法。随着互联网技术的快速发展,分布式系统已经成为支撑大规模服务的关键技术之一。在分布式系统中,多个节点通过网络协同工作,提供高可用性...
整合SSH框架与Redis,主要是为了让SSH应用能够利用Redis的高速缓存能力,提升数据读取速度,减轻数据库的压力。以下是整合的步骤和关键知识点: 1. **相关Jar文件**:为了实现SSH与Redis的整合,需要引入Redis...
这个"redis整合包.zip"包含的是Redis的Windows安装程序(Redis-x64-3.2.100.msi)和一个Redis桌面管理工具(redisdesktopmanager.rar)。以下是对这两个关键组件的详细说明: **Redis-x64-3.2.100.msi** 这是Redis ...
在IT行业中,SSH(Spring、Struts2、Hibernate)是一个经典的Java Web开发框架组合,而Redis则是一个高性能的键值存储系统,常用于缓存和数据持久化。将SSH与Redis整合,可以提升应用程序的性能和响应速度。下面将...
SpringBoot与Redis整合是现代Java开发中常见的技术组合,尤其适用于构建高性能、高并发的Web应用。SpringBoot简化了配置和集成第三方库的过程,而Redis则作为内存数据存储,提供了高速的数据读写能力。以下是对这个...
这种整合方式不仅提高了代码的可读性和可维护性,也充分利用了Redis的高效性能,为应用程序带来了更好的用户体验。在实际开发中,还可以根据需求扩展到其他Redis功能,如发布/订阅、Sorted Set等。
此外,一致性哈希算法在分布式缓存如Memcached、Redis中也得到了广泛应用。它不仅简化了数据分布的逻辑,还允许动态扩展和收缩集群规模,无需大规模的数据迁移。 在文件名为“distribute-mysql”的压缩包中,可能...
将SpringBoot、Shiro和Redis整合,主要目的是利用Shiro进行用户认证和授权,而Redis作为Session的共享存储,解决分布式环境下的会话一致性问题。以下是整合步骤: 1. **引入依赖**:在SpringBoot的pom.xml文件中...
在IT行业中,Spring框架与Redis的整合是常见的数据缓存和会话管理解决方案。这个"spring+redis整合"项目展示了如何利用Spring框架和Redis数据库来实现一个高效的、高可用的登录系统,其中会话(Session)由Redis进行...
在IT行业中,Spring框架与Redis的整合是常见的数据缓存技术应用,...以上就是关于"spring+redis整合demo"中的主要知识点。通过学习和理解这些内容,你可以熟练地在Spring应用中集成Redis,提升系统的性能和响应速度。
RedisJumphash提供了非常快速的一致性哈希函数,以使用Redis构建分布式系统。 用法 JUMPHASH <key> 成功调用将返回给定密钥的存储桶。 它不需要任何存储。 如果您更改存储桶的数量,该算法将保证需要的重定位次数...
redis基本命令 一、关系数据库与非关系数据库 1.1. 关系型数据库 关系型数据库是一个结构化的数据库,创建在关系模型(二维表格模型)基础上,一般面向于记录。 SQL 语句(标准数据查询语言)就是一种基于...
总结,将Redis整合到Tomcat集群中,主要涉及Redis的使用、Tomcat的会话管理机制、配置自定义Session Manager以及系统性能和安全性的考量。这种集成使得会话能够在多台Tomcat服务器之间无缝切换,提高了应用的可用性...
此外,Spring Data Redis还提供了其他高级操作,如opsForHash()、opsForList()、opsForSet()和opsForZSet(),分别对应Redis中的哈希、列表、集合和有序集合数据结构,可以方便地进行复杂的数据操作。 总之,"dx-...
此“redis整合包”包含了用于在单机和集群环境中搭建Redis服务所需的所有组件,确保用户能够顺利进行安装和配置。 首先,`redis-3.0.0.gem` 是Redis服务器的RubyGem包。RubyGem是Ruby编程语言的标准包管理器,`gem`...
它们都提供了一系列操作方法,如`opsForValue()`用于处理单一值,`opsForHash()`处理哈希,`opsForSet()`处理集合,`opsForZSet()`处理有序集合等。 6. **缓存注解** Spring提供了一系列缓存注解,如`@Cacheable`...