溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

利用php怎么實(shí)現(xiàn)memcache一致性hash

發(fā)布時(shí)間:2020-12-24 15:39:17 來源:億速云 閱讀:158 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章給大家介紹利用php怎么實(shí)現(xiàn)memcache一致性hash,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

實(shí)現(xiàn)過程:

memcache的配置 ip+端口+虛擬節(jié)點(diǎn)序列號(hào) 做hash,使用的是crc32,形成一個(gè)閉環(huán)。
對(duì)要操作的key進(jìn)行crc32
二分法在虛擬節(jié)點(diǎn)環(huán)中查找最近的一個(gè)虛擬節(jié)點(diǎn)
從虛擬節(jié)點(diǎn)中提取真實(shí)的memcache ip和端口,做單例連接

復(fù)制代碼 代碼如下:


<?php
class memcacheHashMap {
        private $_node = array();
        private $_nodeData = array();
        private $_keyNode = 0;
        private $_memcache = null;
        //每個(gè)物理服務(wù)器生成虛擬節(jié)點(diǎn)個(gè)數(shù) [注:節(jié)點(diǎn)數(shù)越多,cache分布的均勻性越好,同時(shí)set get操作時(shí),也更耗資源,10臺(tái)物理服務(wù)器,采用200較為合理]
        private $_virtualNodeNum = 200;
        private function __construct() {
                $config = array(//五個(gè)memcache服務(wù)器
                                                '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 < $this->_virtualNodeNum; $i++) {
                                $this->_node[sprintf("%u", crc32($value . '_' . $i))] = $value . '_' . $i;//循環(huán)為每個(gè)memcache服務(wù)器創(chuàng)建200個(gè)虛擬節(jié)點(diǎn)
                        }
                }
                ksort($this->_node);//創(chuàng)建出來的1000個(gè)虛擬節(jié)點(diǎn)按照鍵名從小到大排序
        }
        //實(shí)例化該類
        static public function getInstance() {
                static $memcacheObj = null;
                if (!is_object($memcacheObj)) {
                        $memcacheObj = new self();
                }
                return $memcacheObj;
        }
        //根據(jù)傳來的鍵查找到對(duì)應(yīng)虛擬節(jié)點(diǎn)的位置
        private function _connectMemcache($key) {
                $this->_nodeData = array_keys($this->_node);//所有的虛擬節(jié)點(diǎn)的鍵的數(shù)組
                $this->_keyNode = sprintf("%u", crc32($key));//算出鍵的hash值
                $nodeKey = $this->_findServerNode();//找出對(duì)應(yīng)的虛擬節(jié)點(diǎn)
                //如果超出環(huán),從頭再用二分法查找一個(gè)最近的,然后環(huán)的頭尾做判斷,取最接近的節(jié)點(diǎn)
                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];
        }
        //二分法根據(jù)給出的值找出最近的虛擬節(jié)點(diǎn)位置
        private function _findServerNode($m = 0, $b = 0) {
            $total = count($this->_nodeData);
            if ($total != 0 && $b == 0) $b = $total - 1;
            if ($m < $b){
                $avg = intval(($m+$b) / 2);
                if ($this->_nodeData[$avg] == $this->_keyNode) return $this->_nodeData[$avg];
                elseif ($this->_keyNode < $this->_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) < abs($this->_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);
//測(cè)試一萬次set加get
for($i=0;$i<10000;$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<10000;$i++) {
        $key = md5(mt_rand());
        $b = $m->set($key, time(), 0, 10);
}
var_dump(number_format(microtime(true) - $runData['BEGIN_TIME'],6));
?>

關(guān)于利用php怎么實(shí)現(xiàn)memcache一致性hash就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI