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

php连接redis集群 CodeIgniter(ci)框架redis5集群RedisClustert类使用,php redis集群加密码调用_第1张图片

 修改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完整源码: 


 * @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();
            }
        }
    }
}

 

你可能感兴趣的:(redis,php,CodeIgniter,redis集群,ci,redis集群,php连接redis集群)