php連接redis集羣 CodeIgniter(ci)框架redis5集羣RedisClustert類使用,php redis集羣加密碼調用

注意:如果redis集羣配置了密碼,需要把php環境升級到php7.3,不然無法使用

redis5集羣搭建(集羣加密)看這裏:https://blog.csdn.net/u011477914/article/details/89384206

RedisClustert類用法參考:https://github.com/phpredis/phpredis/blob/develop/cluster.markdown#readme

 修改CodeIgniter\system\libraries\Cache\drivers\Cache_redis.php文件

1、使用redis集羣調用方法:

protected $_cluster_config= Array('10.1.1.198:6000', '10.1.1.198:6001', '10.1.1.198:6002', '10.1.1.198:6003', '10.1.1.198:6004', '10.1.1.198:6005');

//無密碼訪問
$this->redis = new RedisCluster(NULL,$_cluster_config);

//密碼訪問
$this->redis = new RedisCluster(NULL, $this->_cluster_config, '1.5', '1.5', false, "a123456");

2、修改部分方法:【原先的$this->redis->delete($key)   更新爲 $this->redis->del($key)】


	public function delete($key, $type = 'string')
	{
        if($this->redisShow) {
            switch ($type){
                case 'string':
                    //刪除單個
                    $key = $this->prefix . $key;
                    break;
                case 'array':
                    //刪除指定數組
                    $keyArr = [];
                    foreach ($key as $value){
                        $keyArr[] = $this->prefix . $value;
                    }
                    $key = $keyArr;
                    break;
                case 'keys':
                    //模糊刪除
                    $key = $this->prefix . $key;
                    $key = $this->redis->keys($key.'*');
                    break;
            }
            return ($this->redis->del($key) === 1);
        }
        return false;
	}

 3、$this->redis->info()  修改爲: $this->redis->info(uniqid())

public function cache_info()
{
    if($this->redisShow) {
        return $this->redis->info(uniqid());
    }
    return false;
}

其他功能和單機功能一樣,可以直接使用。

4、Cache_redis.php完整源碼: 

<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014 - 2017, British Columbia Institute of Technology
 *
 * 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.
 *
 * @package	CodeIgniter
 * @author	EllisLab Dev Team
 * @copyright	Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
 * @copyright	Copyright (c) 2014 - 2017, British Columbia Institute of Technology (http://bcit.ca/)
 * @license	http://opensource.org/licenses/MIT	MIT License
 * @link	https://codeigniter.com
 * @since	Version 3.0.0
 * @filesource
 */
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * CodeIgniter Redis Caching Class
 *
 * @package	   CodeIgniter
 * @subpackage Libraries
 * @category   Core
 * @author	   Anton Lindqvist <[email protected]>
 * @link
 */
class CI_Cache_redis extends CI_Driver
{
    //CI實例
    protected $CI;

    /**
     * Prefixed to all cache names.
     *
     * @var string
     */
    protected $_prefix = 'DH_';

    /**
     * Default config
     *
     * @static
     * @var	array
     */
    protected static $_default_config = array(
        'socket_type' => 'tcp',
        'host' => '127.0.0.12',
        'password' => 'a123456',
        'port' => 6379,
        'timeout' => 0
    );

    /**
     * Cluster config
     *
     * @static
     * @var	array
     */
    protected $_cluster_config = array('10.1.1.198:6000', '10.1.1.198:6001', '10.1.1.198:6002', '10.1.1.198:6003', '10.1.1.198:6004', '10.1.1.198:6005');

    /**
     * Redis connection
     *
     * @var	Redis
     */
    protected $redis;

    /**
     * Redis connection
     * 判斷redis服務是否正常啓用
     * @var	Redis
     */
    protected $_redisShow = 1;

    /**
     * An internal cache for storing keys of serialized values.
     *
     * @var	array
     */
    protected $_serialized = array();

    // ------------------------------------------------------------------------

    /**
     * Class constructor
     *
     * Setup Redis
     *
     * Loads Redis config file if present. Will halt execution
     * if a Redis connection can't be established.
     *
     * @return	void
     * @see		Redis::connect()
     */
    public function __construct()
    {
        if ( ! $this->is_supported())
        {
            $this->_redisShow = '0';
        }

            try {
                $this->redis = new RedisCluster(NULL, $this->_cluster_config, '1.5','1.5',false,"a123456");
            }catch (RedisClusterException $e) {
                $config = self::$_default_config;
                $this->redis = new Redis();
                try {
                    if ($config['socket_type'] === 'unix') {
                        $success = $this->redis->connect($config['socket']);
                    } else // tcp socket
                    {
                        $success = $this->redis->connect($config['host'], $config['port'], $config['timeout']);
                    }

                    if (!$success) {
                        $this->_redisShow = '0';
                    }

                    if (isset($config['password']) && !$this->redis->auth($config['password'])) {
                        $this->_redisShow = '0';
                    }
                } catch (RedisException $e) {
                    $this->_redisShow = '0';
                }
            }
     
    }

    /**
     * Get cache
     *
     * @param	string	$key	Cache ID
     * @return	mixed
     */
    public function get($key)
    {
        if($this->_redisShow) {
            $key = $this->_prefix . $key;
            $data = $this->redis->hMGet($key, ['__ci_type', '__ci_value']);

            if ( ! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false)
            {
                return false;
            }

            switch ($data['__ci_type'])
            {
                case 'array':
                case 'object':
                    return unserialize($data['__ci_value']);
                case 'boolean':
                case 'integer':
                case 'double': // Yes, 'double' is returned and NOT 'float'
                case 'string':
                case 'NULL':
                    return settype($data['__ci_value'], $data['__ci_type']) ? $data['__ci_value'] : false;
                case 'resource':
                default:
                    return false;
            }
        }
        return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Save cache
     *
     * @param	string	$key	Cache ID
     * @param	mixed	$value	Data to save
     * @param	int	$ttl	Time to live in seconds
     * @param	bool	$raw	Whether to store the raw value (unused)
     * @return	bool	TRUE on success, FALSE on failure
     */
    public function save($key, $value, $ttl = 60)
    {
        if($this->_redisShow) {
            $key = $this->_prefix . $key;
            switch ($data_type = gettype($value))
            {
                case 'array':
                case 'object':
                    $value = serialize($value);
                    break;
                case 'boolean':
                case 'integer':
                case 'double': // Yes, 'double' is returned and NOT 'float'
                case 'string':
                case 'NULL':
                    break;
                case 'resource':
                default:
                    return false;
            }

            if ( ! $this->redis->hMSet($key, ['__ci_type' => $data_type, '__ci_value' => $value]))
            {
                return false;
            }
            elseif ($ttl)
            {
                if($ttl == '3600') $ttl = $ttl*12;
                $this->redis->expireAt($key, time() + $ttl);
            }
            return true;
        }
        return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Delete from cache
     *
     * @param	string|array	$key	Cache key
     * @param	string	$type	string刪除單個|array刪除指定數組|keys模糊刪除
     * @return	bool
     */
    public function delete($key, $type = 'string')
    {
        if($this->_redisShow) {
            switch ($type){
                case 'string':
                    //刪除單個
                    $key = $this->_prefix . $key;
                    break;
                case 'array':
                    //刪除指定數組
                    $keyArr = [];
                    foreach ($key as $value){
                        $keyArr[] = $this->_prefix . $value;
                    }
                    $key = $keyArr;
                    break;
                case 'keys':
                    //模糊刪除
                    $key = $this->_prefix . $key;
                    $key = $this->redis->keys($key.'*');
                    break;
            }
            return ($this->redis->del($key) === 1);
        }
        return false;
    }


    // ------------------------------------------------------------------------

    /**
     * Increment a raw value
     *
     * @param	string	$key    Cache ID
     * @param	int	$offset	Step/value to add
     * @return	mixed	New value on success or FALSE on failure
     */
    public function increment($key, $offset = 1)
    {
        if($this->_redisShow) {
            $key = $this->_prefix . $key;
            return $this->redis->hIncrBy($key, 'data', $offset);
            // return $this->_redis->incr($id, $offset);
        }
        return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Decrement a raw value
     *
     * @param	string	$key	Cache ID
     * @param	int	$offset	Step/value to reduce by
     * @return	mixed	New value on success or FALSE on failure
     */
    public function decrement($key, $offset = 1)
    {
        if($this->_redisShow) {
            $key = $this->_prefix . $key;
            // return $this->_redis->decr($id, $offset);
            return $this->redis->hIncrBy($key, 'data', -$offset);
        }
        return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Clean cache
     *
     * @return	bool
     * @see		Redis::flushDB()
     */
    public function clean()
    {
        //$this->initialize(self::$_master_config);
        if($this->_redisShow) {
            return $this->redis->flushDB();
        }
        return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Get cache driver info
     *
     * @param	string	$type	Not supported in Redis.
     *				Only included in order to offer a
     *				consistent cache API.
     * @return	array|string
     * @see		Redis::info()
     */
    public function cache_info()
    {
        if($this->_redisShow) {
            return $this->redis->info(uniqid());
        }
        return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Get cache metadata
     *
     * @param	string	$key	Cache key
     * @return	array|FALSE|string
     */
    public function get_metadata($key)
    {
        if($this->_redisShow) {
            $key = $this->_prefix . $key;
            $value = $this->get($key);

            if ($value !== FALSE)
            {
                $time = time();
                return [
                    'expire' => $time + $this->redis->ttl($key),
                    'mtime' => $time,
                    'data' => $value
                ];
            }

            return FALSE;
        }
        return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Check if Redis driver is supported
     *
     * @return	bool
     */
    public function is_supported()
    {
        if($this->_redisShow) {
            return extension_loaded('redis');
        }
        return false;
    }

    // ------------------------------------------------------------------------

    /**
     * Class destructor
     *
     * Closes the connection to Redis if present.
     *
     * @return	void
     */
    public function __destruct()
    {
        if($this->_redisShow) {
            if ($this->redis) {
                $this->redis->close();
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章