最近在看一些分布式方面的文章,所以就用php实现一致性hash来练练手,以前一般用的是最原始的hash取模做分布式,当生产过程中添加或删除一台memcache都会造成数据的全部失效,一致性hash就是为了解决这个问题,把失效数据降到最低,相关资料可以google一下!
php实现效率有一定的缺失,如果要高效率,还是写扩展比较好
经测试,5个memcache,每个memcache生成100个虚拟节点,set加get1000次,与单个memcache直接set加get慢5倍,所以效率一般,有待优化!
实现过程:
  • memcache的配置 ip+端口+虚拟节点序列号 做hash,使用的是crc32,形成一个闭环。
  • 对要操作的key进行crc32
  • 二分法在虚拟节点环中查找最近的一个虚拟节点
  • 从虚拟节点中提取真实的memcache ip和端口,做单例连接
<?php
/**
* 一致性哈希memcache分布式,采用的是虚拟节点的方式解决分布均匀性问题,查找节点采用二分法快速查找
* the last known user to change this file in the repository <$LastChangedBy: nash.xiong [ DISCUZ_CODE_0 ]gt;
* @author nash.xiong <nash.xiong@gmail.com>
* @copyright Copyright &copy; 2003-2012 phpd.cn
* @license
*/
class memcacheHashMap { private $_node = array();
private $_nodeData = array();
private $_keyNode = ;
private $_memcache = null; //每个物理服务器生成虚拟节点个数 [注:节点数越多,cache分布的均匀性越好,同时set get操作时,也更耗资源,10台物理服务器,采用200较为合理]
private $_virtualNodeNum = ; private function __construct() {
/* 放入配置文件 */
$config = array(
'127.0.0.1:11211',
'127.0.0.1:11212',
'127.0.0.1:11213',
'127.0.0.1:11214',
'127.0.0.1:11215'
); if (!$config) throw new Exception('Cache config NULL');
foreach ($config as $key => $value) {
for ($i = ; $i < $this->_virtualNodeNum; $i++) {
$this->_node[sprintf("%u", crc32($value . '_' . $i))] = $value . '_' . $i;
}
}
ksort($this->_node);
} private function __clone(){} /**
* 单例,保证只有一个实例
*/
static public function getInstance() {
static $memcacheObj = null;
if (!is_object($memcacheObj)) {
$memcacheObj = new self();
}
return $memcacheObj;
} /**
* 根据key做一致性hash后连接到一台物理memcache服务器
* @param string $key
*/
private function _connectMemcache($key) {
$this->_nodeData = array_keys($this->_node);
$this->_keyNode = sprintf("%u", crc32($key));
$nodeKey = $this->_findServerNode();
//如果超出环,从头再用二分法查找一个最近的,然后环的头尾做判断,取最接近的节点
if ($this->_keyNode > end($this->_nodeData)) {
$this->_keyNode -= end($this->_nodeData);
$nodeKey2 = $this->_findServerNode();
if (abs($nodeKey2 - $this->_keyNode) < abs($nodeKey - $this->_keyNode)) $nodeKey = $nodeKey2;
}
var_dump($this->_node[$nodeKey]);
list($config, $num) = explode('_', $this->_node[$nodeKey]);
if (!$config) throw new Exception('Cache 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 unknown_type $m
* @param unknown_type $b
*/
private function _findServerNode($m = , $b = ) {
$total = count($this->_nodeData);
if ($total != && $b == ) $b = $total - ;
if ($m < $b){
$avg = intval(($m+$b) / );
if ($this->_nodeData[$avg] == $this->_keyNode) return $this->_nodeData[$avg];
elseif ($this->_keyNode < $this->_nodeData[$avg] && ($avg- >= )) return $this->_findServerNode($m, $avg-);
else return $this->_findServerNode($avg+, $b);
}
if (abs($this->_nodeData[$b] - $this->_keyNode) < abs($this->_nodeData[$m] - $this->_keyNode)) return $this->_nodeData[$b];
else return $this->_nodeData[$m];
} public function set($key, $value, $expire = ) {
return $this->_connectMemcache($key)->set($key, json_encode($value), , $expire);
} public function add($key, $value, $expire = ) {
return $this->_connectMemcache($key)->add($key, json_encode($value), , $expire);
} public function get($key) {
return json_decode($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=;$i<;$i++) {
$key = md5(mt_rand());
$b = memcacheHashMap::getInstance()->set($key, time(), );
} var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],));
$runData['BEGIN_TIME'] = microtime(true); $m= new Memcache;
$m->connect('127.0.0.1', );
for($i=;$i<;$i++) {
$key = md5(mt_rand());
$b = $m->set($key, time(), , );
}
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],));

//测试结果,采用一致性哈希分布效率比原生单台速度相差5倍左右

memcache分布式 [一致性hash算法] 的php实现的更多相关文章

  1. 分布式一致性hash算法

    写在前面  在学习Redis的集群内容时,看到这么一句话:Redis并没有使用一致性hash算法,而是引入哈希槽的概念.而分布式缓存Memcached则是使用分布式一致性hash算法来实现分布式存储. ...

  2. memcache的一致性hash算法使用

    一.概述 1.我们的memcache客户端(这里我看的spymemcache的源码),使用了一致性hash算法ketama进行数据存储节点的选择.与常规的hash算法思路不同,只是对我们要存储数据的k ...

  3. memcache的一致性hash算法

    <?php /** * 一致性哈希memcache分布式,采用的是虚拟节点的方式解决分布均匀性问题,查找节点采用二分法快速查找 * the last known user to change t ...

  4. 关于memcache分布式一致性hash

    consistent hashing 算法早在 1997 年就在论文 Consistent hashing and random trees 中被提出,目前在 cache 系统中应用越来越广泛: 1  ...

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

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

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

    分布式一致性hash算法简介 当你看到"分布式一致性hash算法"这个词时,第一时间可能会问,什么是分布式,什么是一致性,hash又是什么.在分析分布式一致性hash算法原理之前, ...

  7. Nginx+Memcache+一致性hash算法 实现页面分布式缓存(转)

    网站响应速度优化包括集群架构中很多方面的瓶颈因素,这里所说的将页面静态化.实现分布式高速缓存就是其中的一个很好的解决方案... 1)先来看看Nginx负载均衡 Nginx负载均衡依赖自带的 ngx_h ...

  8. 一致性Hash算法在Redis分布式中的使用

    由于redis是单点,但是项目中不可避免的会使用多台Redis缓存服务器,那么怎么把缓存的Key均匀的映射到多台Redis服务器上,且随着缓存服务器的增加或减少时做到最小化的减少缓存Key的命中率呢? ...

  9. 分布式缓存一致性hash算法理解

    今天阅读了一下大型网络技术架构这本苏中的分布式缓存一致性hash算法这一节,针对大型分布式系统来说,缓存在该系统中必不可少,分布式集群环境中,会出现添加缓存节点的需求,这样需要保障缓存服务器中对缓存的 ...

随机推荐

  1. Java单例模式实现的几种方式

    单例模式好多书上都是这么写的: public class SingleTon1 { private SingleTon1(){ } private static SingleTon1 instance ...

  2. iOS之 APNs全新的APNs苹果15年WWDC大会上的干货

    记得14年在dl某大学校招上现场面试iOS时候被问到了APNs也就是苹果的推送问题,当时我表示一脸懵逼,因为当时还没有真正接触做过项目也就了解了个大概,总之当时回答的一塌糊涂!后来回去就在网上仔细查了 ...

  3. WPF学习之路(十三)URL

    URL一般由三个部分组成,协议.资源所在主机地址.资源路径 WPF中URL同样有三部分组成:pack.authority(application:| siteoforigin:).路径 资源文件 本地 ...

  4. 你知道哪些linux命令,能把文件上传到远程linux服务器

    多数情况下 企业的服务基本都是部署在linux服务器 那对于测试同学,必须掌握基本的linux命令   至少要知道怎么部署整体环境   部署过程中,经常需要的操作,是向服务器上传部署包   你一般都是 ...

  5. Javascript之旅——第五站:说说那些所谓的包装类型

    最近不看犀牛书了,那本翻译的特烂而且好拗口,尤其是原型那块说的乱七八糟,后来经同事介绍,买了本js高级程序设计,然后就继续 苦逼的看,不吐槽了,继续说说js中有新鲜感的包装类型. 一:String 说 ...

  6. Consul 启动命令

    服务端: nohup consul agent -server -bootstrap-expect 1 -config-dir /etc/consul.d/ -data-dir /var/opt/co ...

  7. nginx有关.htaccess小结

    可能很多朋友都常用nginx不支持.htaccess,只有apache才支持.htaccess文件,其实这是错误的看法nginx也是支持.hatccess的哦. 其实nginx和.htaccess一点 ...

  8. 使用.Net自带的GZipStream进行流压缩与解压

    using System.IO; using System.IO.Compression; using System.Text; namespace CS.Utility { /// <summ ...

  9. Java魔法堂:找外援的利器——Runtime.exec详解

    一.前言 Java虽然五脏俱全但总有软肋,譬如获取CPU等硬件信息,当然我们可以通过JNI调用C/C++来获取,但对于对C/C++和Windows API不熟的码农是一系列复杂的学习和踩坑过程.那能不 ...

  10. hdu 4967 Handling the Past

    hdu 4967 Handling the Past view code//把时间离散化,维护一个线段(线段l到r的和用sum[l,r]表示),pop的时候就在对应的时间减一,push则相反 //那么 ...