ThinkPHP 3.2.3 SESSION Redis驱动扩展

浏览:4117 发布日期:2017/08/01 分类:系统代码 关键字: session redis 驱动 扩展 thinkphp 3.2.3
ThinkPHP3.2.3 SESSION Redis 驱动
放到Library/Think/Session/Driver目录下即可
详细配置,请看类文件注释<?php

namespace Think\Session\Driver;

/**
 * Class Redis
 * @package Think\Session\
 *
 *  // 配置示例
 *  'SESSION_AUTO_START' => true, //是否开启session
 *  'SESSION_OPTIONS'    => [
 *      'type'   => 'Redis',
 *      'expire' => isMobile() ? 86400 : 7200,// 平台判断 手机 1 天,其他 2 小时
 *      'config' => 'session',
 *  ],
 *
 *  // Redis多组配置
 *  'REDIS_CONFIG' => [
 *      'session' => [
 *          'HOST' => '127.0.0.1',
 *          'PORT' => '3306',
 *          'PASSWORD' => false,
 *          'PREFIX' => 'zentrust_cn_sess:',
 *          'DB' => 0,
 *      ],
 *  ],
 */
class Redis
{
    /**
     * Session有效时间
     */
    protected $lifeTime = '';

    /**
     * 数据库句柄
     */
    protected $hander = [];

    protected $config = [
        'HOST'     => '127.0.0.1', // 主机地址 支持 逗号 分隔多组
        'PORT'     => 6379,// 端口地址 支持 逗号 分隔多组
        'DB'       => 0,// 数据库 多组 逗号分隔
        'PASSWORD' => 0,// 密码 多组 逗号分隔
        'PREFIX'   => 'zentrust_cn_sess:',// 前缀
        'DEPLOY_TYPE' => 0,// 分布式
        'RW_SEPARATE' => 0,// 读写分离(必须开启分布式)
        'MASTER_NO' => 0,// 主服务器配置序号
        'SLAVE_NO' => 0,// 从服务器配置序号
        'PERSISTENT' => true,// 长连接 默认开启
    ];

    /**
     * 打开Session
     * @access public
     *
     * @param string $savePath
     * @param mixed  $sessName
     */
    public function open($savePath, $sessName)
    {
        // 检测php环境
        if (!extension_loaded('redis')) {
            throw new \Exception('not support:redis');
        }
        // 加载配置
        $config = C('REDIS_CONFIG')[C('SESSION_OPTIONS')['config']];

        $this->config = array_merge($this->config, $config);

        $this->lifeTime = C('SESSION_EXPIRE') ? C('SESSION_EXPIRE') : ini_get('session.gc_maxlifetime');

        //分布式Redis
        $redis = new \Redis();
        $host = explode(',', $config['HOST']);
        $port = explode(',', $config['PORT']);
        $pwd = explode(',', $config['PASSWORD']);
        $db = explode(',', $config['DB']);
        if (1 == $config['DEPLOY_TYPE']) {
            //读写分离
            if ($config['RW_SEPARATE']) {
                $w = $config['MASTER_NO'];
                if (is_numeric($config['SLAVE_NO']) && $config['SLAVE_NO'] > 0) {//指定服务器读
                    $r = $config['SLAVE_NO'];
                } else {
                    $r = floor(mt_rand($config['MASTER_NO'], count($host) - 1));
                }
                // 主数据库链接
                $db_host = $host[$w];
                $db_port = (isset($port[$w]) ? $port[$w] : $port[0]);
                $db_pwd = isset($pwd[$w]) ? $pwd[$w] : $pwd[0];
                $func = $this->config['PERSISTENT'] ? 'pconnect' : 'connect';
                $redis->$func($db_host, $db_port);
                $redis->select($db[$w]);
                if($db_pwd){
                    $redis->auth($db_pwd);
                }
                $this->hander[0] = $redis;
                //从数据库链接
                $db_host = $host[$r];
                $db_port = (isset($port[$r]) ? $port[$r] : $port[0]);
                $db_pwd = isset($pwd[$r]) ? $pwd[$r] : $pwd[0];
                $redis->$func($db_host, $db_port);
                $redis->select($db[$r]);
                if($db_pwd){
                    $redis->auth($db_pwd);
                }
                $this->hander[1] = $redis;
                return true;
            }
        }
        //从数据库链接
        $r = floor(mt_rand(0, count($host) - 1));
        //从数据库链接
        $db_host = $host[$r];
        $db_port = (isset($port[$r]) ? $port[$r] : $port[0]);
        $db_pwd = isset($pwd[$r]) ? $pwd[$r] : $pwd[0];
        $func = $this->config['PERSISTENT'] ? 'pconnect' : 'connect';
        $redis->$func($db_host, $db_port);
        $redis->select($db[$r]);
        if($db_pwd){
            $redis->auth($db_pwd);
        }
        if (!$redis) {
            return false;
        }
        $this->hander = $redis;

        return true;
    }

    /**
     * 关闭Session
     * @access public
     */
    public function close()
    {
        if (is_array($this->hander)) {
            $this->gc($this->lifeTime);
            foreach($this->hander as $k => $v){
                $this->hander[$k]->close();
            }
            return $this->hander = null;
        }
        $this->gc($this->lifeTime);
        $this->hander->close();
        return $this->hander = null;
    }

    /**
     * 读取Session
     * @access public
     *
     * @param string $sessID
     */
    public function read($sessID)
    {
        $hander = is_array($this->hander) ? $this->hander[1] : $this->hander;
        $res = $hander->get($this->config['PREFIX'].$sessID);
        if(!$res){
            return '';
        }
        return $res;
    }

    /**
     * 写入Session
     * @access public
     *
     * @param string $sessID
     * @param String $sessData
     */
    public function write($sessID, $sessData)
    {
        $hander = is_array($this->hander) ? $this->hander[0] : $this->hander;
        $expire = $this->lifeTime;
        $res = $hander->set($this->config['PREFIX'].$sessID, $sessData, $expire);
        if (!$res) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 删除Session
     * @access public
     *
     * @param string $sessID
     */
    public function destroy($sessID)
    {
        $hander = is_array($this->hander) ? $this->hander[0] : $this->hander;
        $count = $hander->delete($this->config['PREFIX'].$sessID);
        if ($count) {
            return true;
        }

        return false;
    }

    /**
     * Session 垃圾回收
     * @access public
     *
     * @param string $sessMaxLifeTime
     */
    public function gc($sessMaxLifeTime)
    {
        // 获取所有keys
        /*$hander = is_array($this->hander) ? $this->hander[0] : $this->hander;
        $keys = $hander->keys($this->config['PREFIX'].'*');
        foreach($keys as $v){
            // 获取keys
            $res = $hander->get($v);
            if(!$res){
                $hander->del($v);
            }
        }*/
        // Redis 自动回收
        return true;
    }
}
评论( 相关
后面还有条评论,点击查看>>