<s id="0oyqk"></s>
  • <option id="0oyqk"><optgroup id="0oyqk"></optgroup></option>
  • <source id="0oyqk"><bdo id="0oyqk"></bdo></source>
  • thinkphp5.0 鏈接redis cluster集群教程(帶密碼)

     更新時間:2019-02-22 11:41:51   作者:佚名   我要評論(0)

    廢話不多說,直接步入正題。在thinkphp\libary\think\cache\driver文件夾內新建RedisCluster.php文件,內容如下:<?php/** * Created by PhpStorm. * User: Caption * Date

    廢話不多說,直接步入正題。在thinkphp\libary\think\cache\driver文件夾內新建RedisCluster.php文件,內容如下:

    <?php
    /**
     * Created by PhpStorm.
     * User: Caption
     * Date: 2019/2/20
     * Time: 下午3:10
     */
    
    namespace think\cache\driver;
    
    use think\cache\Driver;
    
    /**使用phpredis
     * https://github.com/phpredis/phpredis/blob/feature/redis_cluster/cluster.markdown
     * Class RedisCluster
     *
     * @package com\pindakong\tp5ext\driver\cache
     */
    class RedisCluster extends Driver
    {
        /**
         * @var array
         */
        protected $options = [
            //主機或IP,如192.168.0.110,192.168.0.110
            'host'                => '127.0.0.1',//slave host
            //端口,如7001,7002,7003
            'port'                => 6379,
            //鏈接超時時間
            'timeout'             => 1.5,
            //讀取超時時間
            'read_timeout'        => 1.5,
            //過期時間
            'expire'              => 0,
            //持久化鏈接
            'persistent'          => false,
            //緩存前綴
            'prefix'              => '',
            //是否需要json序列化
            'serialize'           => true,
            // 是否需要斷線重連
            'break_reconnect'     => true,
            //最大重試連接次數
            'max_reconnect_times' => 20,
            
            'password'            => '',
        ];
    
        /**
         * @var array
         */
        private static $node_params = [];
    
        /**需要重連的錯誤信息
         *
         * @var array
         */
        private $breakMatchStr = [
            'Connection refused',
        ];
    
        /**
         * 架構函數
         *
         * @access public
         *
         * @param  array $options 緩存參數
         *
         * @throws \Exception
         */
        public function __construct($options = [])
        {
            if (!extension_loaded('redis'))
            {
                throw new \BadFunctionCallException('not support: redis');
            }
    
            if (!empty($options))
            {
                $this->options = array_merge($this->options, $options);
            }
            $this->init_connect();
        }
    
        /**
         * @param int $reconnect_times 重連次數
         *
         * @throws \Exception
         */
        protected function init_connect($reconnect_times = 0)
        {
            //此處進行分布式配置
            $params = array(
                'hosts' => explode(',', $this->options['host']),
                'ports' => explode(',', $this->options['port']),
            );
            //拼接參數
            $hostsNum = count($params['hosts']);
            $seeds = [];
            for ($i = 0; $i < $hostsNum; $i++)
            {
                $host = $params['hosts'][$i];
                $port = $params['ports'][$i] ? $params['ports'][$i] : $params['ports'][0];
                $seeds[$i] = $host . ":" . $port;
            }
            try
            {
                //連接并指定timeout和read_timeout
                $this->handler = new \RedisCluster(NULL, 
                    $seeds, 
                    $this->options["timeout"], 
                    $this->options["read_timeout"],
                    $this->options["persistent"],
                    empty( $this->options['password']) ? NULL :  $this->options['password']
                    );
                
    //             if ('' != $this->options['password']) {
    //                 $this->handler->auth($this->options['password']);
    //             }
                
                // 始終在主機和從機之間隨機分配只讀命令
                $this->handler->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_DISTRIBUTE);
                
                
            }
            catch (\Exception $e)
            {
                if ($this->isBreak($e))
                {
                    if ($reconnect_times <= $this->options['max_reconnect_times'])
                    {
                        echo $reconnect_times . "<br/>";
                        sleep(0.5);
                        $this->init_connect(++$reconnect_times);
                    }
                    else
                    {
                        throw $e;
                    }
                }
                else
                {
                    throw $e;
                }
            }
        }
    
        /**是否斷線
         *
         * @param \Exception $e
         *
         * @return bool
         */
        protected function isBreak(\Exception $e)
        {
            if (!$this->options['break_reconnect'])
            {
                return false;
            }
    
            $error = $e->getMessage();
    
            foreach ($this->breakMatchStr as $msg)
            {
                if (false !== stripos($error, $msg))
                {
                    return true;
                }
            }
            return false;
        }
    
        /**
         * 判斷緩存是否存在
         *
         * @access public
         *
         * @param  string $name 緩存變量名
         *
         * @return bool
         */
        public function has($name)
        {
            // TODO: Implement has() method.
            return $this->handler->exists($this->getCacheKey($name));
        }
    
        /**
         * 讀取緩存
         *
         * @access public
         *
         * @param  string $name    緩存變量名
         * @param  mixed  $default 默認值
         *
         * @return mixed
         */
        public function get($name, $default = false)
        {
            // TODO: Implement get() method.
            $this->readTimes++;
    
            $value = $this->handler->get($this->getCacheKey($name));
    
            if (is_null($value) || false === $value)
            {
                return $default;
            }
    
            return $this->unserialize($value);
        }
    
        /**
         * 寫入緩存
         *
         * @access public
         *
         * @param  string $name   緩存變量名
         * @param  mixed  $value  存儲數據
         * @param  int    $expire 有效時間 0為永久
         *
         * @return boolean
         */
        public function set($name, $value, $expire = null)
        {
            // TODO: Implement set() method.
            $this->writeTimes++;
    
            if (is_null($expire))
            {
                $expire = $this->options['expire'];
            }
    
            if ($this->tag && !$this->has($name))
            {
                $first = true;
            }
    
            $key = $this->getCacheKey($name);
            $expire = $this->getExpireTime($expire);
    
            $value = $this->serialize($value);
    
            if ($expire)
            {
                $result = $this->handler->setex($key, $expire, $value);
            }
            else
            {
                $result = $this->handler->set($key, $value);
            }
    
            isset($first) && $this->setTagItem($key);
    
            return $result;
        }
    
        /**
         * 自增緩存(針對數值緩存)
         *
         * @access public
         *
         * @param  string $name 緩存變量名
         * @param  int    $step 步長
         *
         * @return false|int
         */
        public function inc($name, $step = 1)
        {
            // TODO: Implement inc() method.
            $this->writeTimes++;
    
            $key = $this->getCacheKey($name);
    
            return $this->handler->incrby($key, $step);
        }
    
        /**
         * 自減緩存(針對數值緩存)
         *
         * @access public
         *
         * @param  string $name 緩存變量名
         * @param  int    $step 步長
         *
         * @return false|int
         */
        public function dec($name, $step = 1)
        {
            // TODO: Implement dec() method.
            $this->writeTimes++;
    
            $key = $this->getCacheKey($name);
    
            return $this->handler->decrby($key, $step);
        }
    
        /**
         * 刪除緩存
         *
         * @access public
         *
         * @param  string $name 緩存變量名
         *
         * @return boolean
         */
        public function rm($name)
        {
            // TODO: Implement rm() method.
            $this->writeTimes++;
    
            return $this->handler->del($this->getCacheKey($name));
        }
    
        /**
         * 清除緩存
         *
         * @access public
         *
         * @param  string $tag 標簽名
         *
         * @return boolean
         */
        public function clear($tag = null)
        {
            // TODO: Implement clear() method.
    
            if ($tag)
            {
                // 指定標簽清除
                $keys = $this->getTagItem($tag);
    
                foreach ($keys as $key)
                {
                    $this->handler->del($key);
                }
    
                $this->rm('tag_' . md5($tag));
                return true;
            }
    
            $this->writeTimes++;
    
            return $this->handler->flushDB(self::$node_params);
        }
    
        /**
         * 序列化數據
         *
         * @access protected
         *
         * @param  mixed $data
         *
         * @return string
         */
        protected function serialize($data)
        {
            if (is_scalar($data) || !$this->options['serialize'])
            {
                return $data;
            }
    
            return self::$serialize[2] . json_encode($data);
        }
    
        /**
         * 反序列化數據
         *
         * @access protected
         *
         * @param  string $data
         *
         * @return mixed
         */
        protected function unserialize($data)
        {
            if ($this->options['serialize'] && 0 === strpos($data, self::$serialize[2]))
            {
                return json_decode((substr($data, self::$serialize[3])), true);
            }
            else
            {
                return $data;
            }
        }
    }

    使用方法:在cache.php內加入:

                'type' => 'RedisCluster', // 驅動方式
                'host' => '172.19.0.122,172.19.0.121', // 服務器地址 ip地址一樣也需要重復寫
                'port' => '6379,6380,6381',
                'password'=>'',

    即可使用。

    需要重新編譯phpredis以及搭建redis cluster集群,教程如下:

    http://www.v12dy.com/article/56166.html 

    http://www.v12dy.com/article/56165.html 

    相關文章

    最新評論

    种子磁力搜索器