跳至正文

php 利用 redis 实现 session 存储

编写实现类

实现 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();
    }

}

使用方法

存储 session(set.php)

include('test.php');
new SessionManager();
$_SESSION['a'] = 'b';

使用 session(get.php)

include('test.php');
new SessionManager();
echo $_SESSION['a'];
标签: