cari
Rumahpembangunan bahagian belakangtutorial phpmemcache一致性hash的php实现方法_php技巧

本文实例讲述了memcache一致性hash的php实现方法。分享给大家供大家参考。具体如下:

最近在看一些分布式方面的文章,所以就用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和端口,做单例连接

复制代码 代码如下:

class memcacheHashMap {
        private $_node = array();
        private $_nodeData = array();
        private $_keyNode = 0;
        private $_memcache = null;
        //每个物理服务器生成虚拟节点个数 [注:节点数越多,cache分布的均匀性越好,同时set get操作时,也更耗资源,10台物理服务器,采用200较为合理]
        private $_virtualNodeNum = 200;
        private function __construct() {
                $config = array(//五个memcache服务器
                                                '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 = 0; $i _virtualNodeNum; $i++) {
                                $this->_node[sprintf("%u", crc32($value . '_' . $i))] = $value . '_' . $i;//循环为每个memcache服务器创建200个虚拟节点
                        }
                }
                ksort($this->_node);//创建出来的1000个虚拟节点按照键名从小到大排序
        }
        //实例化该类
        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);//所有的虚拟节点的键的数组
                $this->_keyNode = sprintf("%u", crc32($key));//算出键的hash值
                $nodeKey = $this->_findServerNode();//找出对应的虚拟节点
                //如果超出环,从头再用二分法查找一个最近的,然后环的头尾做判断,取最接近的节点
                if ($this->_keyNode > end($this->_nodeData)) {
                        $this->_keyNode -= end($this->_nodeData);
                        $nodeKey2 = $this->_findServerNode();
                        if (abs($nodeKey2 - $this->_keyNode) _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];
        }
        //二分法根据给出的值找出最近的虚拟节点位置
        private function _findServerNode($m = 0, $b = 0) {
            $total = count($this->_nodeData);
            if ($total != 0 && $b == 0) $b = $total - 1;
            if ($m                 $avg = intval(($m+$b) / 2);
                if ($this->_nodeData[$avg] == $this->_keyNode) return $this->_nodeData[$avg];
                elseif ($this->_keyNode _nodeData[$avg] && ($avg-1 >= 0)) return $this->_findServerNode($m, $avg-1);
                else return $this->_findServerNode($avg+1, $b);
            }
                if (abs($this->_nodeData[$b] - $this->_keyNode) _nodeData[$m] - $this->_keyNode))  return $this->_nodeData[$b];
                else return $this->_nodeData[$m];
        }
        public function set($key, $value, $expire = 0) {
                return $this->_connectMemcache($key)->set($key, json_encode($value), 0, $expire);
        }
        public function add($key, $value, $expire = 0) {
                return $this->_connectMemcache($key)->add($key, json_encode($value), 0, $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=0;$i         $key = md5(mt_rand());
        $b = memcacheHashMap::getInstance()->set($key, time(), 10);
}
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;$i         $key = md5(mt_rand());
        $b = $m->set($key, time(), 0, 10);
}
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));
?>

希望本文所述对大家的php程序设计有所帮助。

Kenyataan
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
在PHP中使用Memcache缓存常见问题及解决办法在PHP中使用Memcache缓存常见问题及解决办法May 16, 2023 am 09:07 AM

在Web应用中,缓存是一个非常重要的技术。缓存可以大大减少数据库和服务器的负载,提高Web应用的性能。Memcache是一种高性能的分布式内存缓存系统,常用于Web应用中。在PHP中使用Memcache缓存,有时会出现一些问题,本文将介绍这些问题及其解决办法。问题一:无法连接到Memcache服务器在使用Memcache缓存时,第一个遇到的问题可能是无法连接

利用Memcache缓存技术提高PHP应用的并发处理能力利用Memcache缓存技术提高PHP应用的并发处理能力May 18, 2023 am 08:12 AM

随着互联网的飞速发展,越来越多的应用程序需要面对大量的并发请求,如何提高应用的并发处理能力成为开发者们需要解决的问题。其中,利用Memcache缓存技术进行并发优化成为了相对较为流行的一种方案。Memcache是一种高效的缓存技术,适用于大型Web应用程序、数据库和分布式系统。其特点是将数据存储于内存中,以实现高速读写操作。在Web应用程序的数据访问过程中,

PHP应用中的Memcache缓存技术如何避免出现数据损坏PHP应用中的Memcache缓存技术如何避免出现数据损坏May 15, 2023 pm 10:01 PM

Memcache是一种在Web应用中常用的缓存技术,对于高并发的应用,它能够减轻数据库的压力,提高数据读取速度,降低系统响应时间。但是,在实际运用中,由于某些原因,会出现缓存数据被破坏的情况。本文主要从以下几个方面来讲述如何避免PHP应用中Memcache缓存技术出现数据损坏的情况。一、数据序列化通常情况下,我们将需要缓存的数据直接以对象形式存储到Memca

Memcache缓存技术在PHP中优化数据交互的实践和思考Memcache缓存技术在PHP中优化数据交互的实践和思考May 17, 2023 pm 09:51 PM

Memcache缓存技术在PHP中优化数据交互的实践和思考在现代的Web应用中,数据交互是一个非常重要的问题,它没有足够的高效性,将会限制Web应用程序的扩展性和性能。为了加快数据交互速度,我们通常的做法是优化数据库的设计、提高硬件的性能和增加服务器容量。但是,这些方法都有一个共同的限制:它们会增加系统的成本。最近几年,Memcache技术在解决这个问题上提

Memcache缓存技术在PHP项目中的应用和实践Memcache缓存技术在PHP项目中的应用和实践May 17, 2023 pm 02:10 PM

Memcache是一种开源的、分布式的缓存技术。它通过将数据存储在内存中,极大地提高了数据的访问速度,从而提升了网站的性能和响应速度。在PHP项目中,Memcache缓存技术也被广泛应用,并且取得了很好的效果。本篇文章将深入探讨Memcache缓存技术在PHP项目中的应用和实践。一、Memcache的原理和优势Memcache是一种内存缓存技术,它可以将数据

利用PHP中的Memcache缓存优化Gzip压缩算法利用PHP中的Memcache缓存优化Gzip压缩算法May 15, 2023 pm 04:31 PM

随着网络技术越来越发达,网站的访问量逐渐增多,为了提升用户体验,我们需要尽可能地减少网页的加载时间和传输数据的大小。其中,Gzip压缩算法是一种经典的数据压缩算法,可以在传输数据时将数据压缩,减少传输数据的大小,从而提升网页的加载速度和用户体验。在使用Gzip压缩算法来优化网站时,我们还可以结合PHP中的Memcache缓存技术来进一步提升网站的性能。一、G

PHP中如何使用Memcache缓存技术对于爬虫进行优化PHP中如何使用Memcache缓存技术对于爬虫进行优化May 16, 2023 pm 02:21 PM

随着互联网技术的发展,网络爬虫越来越被用于数据挖掘、搜索引擎等领域。而大规模的数据采集和处理不仅需要更高效的爬虫算法,同时需要优化处理数据的速度和减少资源消耗。在这个过程中,缓存技术发挥了重要作用,为数据处理和应用的性能提供了帮助。本文介绍如何使用PHP中的Memcache缓存技术对于爬虫进行优化。Memcache是一个高性能的分布式内存对象缓存系统。Mem

如何使用PHP中的Memcache缓存技术提高网站的大并发性能如何使用PHP中的Memcache缓存技术提高网站的大并发性能May 17, 2023 pm 05:00 PM

随着互联网技术的不断发展,网站的用户访问量越来越大,带来的并发访问量也越来越高。为了应对这种高并发访问,常用的手段是使用缓存技术。而在PHP语言中,Memcache缓存技术是一种非常有效的解决方案。Memcache是一种分布式缓存系统,能够将大量的数据缓存在内存中,并能够从内存中快速读取,从而提高网站的响应速度和并发能力。在本文中,我们将介绍如何使用PHP中

See all articles

Alat AI Hot

Undresser.AI Undress

Undresser.AI Undress

Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover

AI Clothes Remover

Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool

Undress AI Tool

Gambar buka pakaian secara percuma

Clothoff.io

Clothoff.io

Penyingkiran pakaian AI

AI Hentai Generator

AI Hentai Generator

Menjana ai hentai secara percuma.

Artikel Panas

R.E.P.O. Kristal tenaga dijelaskan dan apa yang mereka lakukan (kristal kuning)
3 minggu yang laluBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Tetapan grafik terbaik
3 minggu yang laluBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Cara Memperbaiki Audio Jika anda tidak dapat mendengar sesiapa
3 minggu yang laluBy尊渡假赌尊渡假赌尊渡假赌

Alat panas

SublimeText3 versi Mac

SublimeText3 versi Mac

Perisian penyuntingan kod peringkat Tuhan (SublimeText3)

PhpStorm versi Mac

PhpStorm versi Mac

Alat pembangunan bersepadu PHP profesional terkini (2018.2.1).

Versi Mac WebStorm

Versi Mac WebStorm

Alat pembangunan JavaScript yang berguna

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Persekitaran pembangunan bersepadu PHP yang berkuasa

MinGW - GNU Minimalis untuk Windows

MinGW - GNU Minimalis untuk Windows

Projek ini dalam proses untuk dipindahkan ke osdn.net/projects/mingw, anda boleh terus mengikuti kami di sana. MinGW: Port Windows asli bagi GNU Compiler Collection (GCC), perpustakaan import yang boleh diedarkan secara bebas dan fail pengepala untuk membina aplikasi Windows asli termasuk sambungan kepada masa jalan MSVC untuk menyokong fungsi C99. Semua perisian MinGW boleh dijalankan pada platform Windows 64-bit.