php利用redis实现session存储

1. 安装redis扩展

安装redis扩展之前需要安装php-dev模块提供phpize,然后使用pecl安装(需安装pecl模块)

    sudo pecl install redis

然后把extension=redis.so加入php.ini即可。当然也可以自行下载源码包编译安装(自行百度)。

2. 编写实现类

编写实现类,实现session_set_save_handler函数参数的各个方法。

class SessionManager
{
    /**
     * redis连接句柄
     * @var Redis $redis
     */
    private $redis;
    /**
     * session过期时间,由redis过期时间控制
     * @var int $expire_time
     */
    private $expire_time=60;

    public function __construct(){
        $this->redis = new Redis();
        $this->redis->connect('127.0.0.1', 6379);
        //授权
        $this->redis->auth("123456");
        session_set_save_handler(
            array($this,"open"),
            array($this,"close"),
            array($this,"read"),
            array($this,"write"),
            array($this,"destroy"),
            array($this,"gc")
        );
        session_start();
    }

    /**
     * 打开session
     * @return bool
     */
    public function open()
    {
        return true;
    }

    /**
     * 关闭session
     * @return bool
     */
    public function close()
    {
        return true;
    }

    /**
     * 读取session
     * @param $id
     * @return bool|string
     */
    public function read($id)
    {
        $value = $this->redis->get($id);
        if($value){
            return $value;
        }else{
            return '';
        }
    }

    /**
     * 设置session
     * @param $id
     * @param $data
     * @return bool
     */
    public function write($id, $data)
    {
        if($this->redis->set($id, $data)) {
            $this->redis->expire($id, $this->expire_time);
            return true;
        }
        return false;
    }

    /**
     * 销毁session
     * @param $id
     * @return bool
     */
    public function destroy($id)
    {
        if($this->redis->delete($id)) {
            return true;
        }
        return false;
    }

    /**
     * gc回收
     * @return bool
     */
    public function gc(){
        return true;
    }

    public function __destruct(){
        session_write_close();
    }

}

3. 使用方法

存储session(set.php)
include('test.php');
new SessionManager();
$_SESSION['a'] = 'b';
使用session(get.php)
include('test.php');
new SessionManager();
echo $_SESSION['a'];
posted @ 2018-10-23 16:19  Christopher丶  阅读(1252)  评论(0编辑  收藏  举报