PHP實現redis儲存session,phpredissession

來源:互聯網
上載者:User

PHP實現redis儲存session,phpredissession

一、首先實現SessionHandlerInterface(此介面PHP>5.4.0),如下

<?php/** * 以db的方式儲存session */namespace OC\Session;class redisSession implements \SessionHandlerInterface{    /**     * 儲存session的redis的資訊     */    private $_options = array(        'handler' => null, //redis串連控制代碼        'host' => null,        'port' => null,        'lifeTime' => null,    );    /**     * 建構函式     * @param $options 設定資訊數組     */    public function __construct($options=array()){        if(!class_exists("redis", false)){            die("必須安裝redis擴充");        }        if(!isset($options['lifeTime']) || $options['lifeTime'] <= 0){            $options['lifeTime'] = ini_get('session.gc_maxlifetime');        }        $this->_options = array_merge($this->_options, $options);    }    /**     * 開始使用該驅動的session     */    public function begin(){        if($this->_options['host'] === null ||            $this->_options['port'] === null ||            $this->_options['lifeTime'] === null        ){            return false;        }        //設定session處理函數        session_set_save_handler(            array($this, 'open'),            array($this, 'close'),            array($this, 'read'),            array($this, 'write'),            array($this, 'destory'),            array($this, 'gc')        );    }    /**     * 自動開始回話或者session_start()開始回話後第一個調用的函數     * 類似於建構函式的作用     * @param $savePath 預設的儲存路徑     * @param $sessionName 預設的參數名,PHPSESSID     */    public function open($savePath, $sessionName){        if(is_resource($this->_options['handler'])) return true;        //串連redis        $redisHandle = new \Redis();        $redisHandle->connect($this->_options['host'], $this->_options['port']);        if(!$redisHandle){            return false;        }        $this->_options['handler'] = $redisHandle;        $this->gc(null);        return true;    }    /**     * 類似於解構函式,在write之後調用或者session_write_close()函數之後調用     */    public function close(){        return $this->_options['handler']->close();    }    /**     * 讀取session資訊     * @param $sessionId 通過該Id唯一確定對應的session資料     * @return session資訊/空串     */    public function read($sessionId){        return $this->_options['handler']->get($sessionId);    }    /**     * 寫入或者修改session資料     * @param $sessionId 要寫入資料的session對應的id     * @param $sessionData 要寫入的資料,已經序列化過了     */    public function write($sessionId, $sessionData){        return $this->_options['handler']->setex($sessionId, $this->_options['lifeTime'], $sessionData);    }    /**     * 主動銷毀session會話     * @param $sessionId 要銷毀的會話的唯一id     */    public function destroy($sessionId){        return $this->_options['handler']->delete($sessionId) >= 1 ? true : false;    }    /**     * 清理繪畫中的到期資料     * @param 有效期間     */    public function gc($lifeTime){        //擷取所有sessionid,讓到期的釋放掉        $this->_options['handler']->keys("*");        return true;    }}
以上就是一個完整的實現介面的類,在此封裝成一個檔案
二、調用時使用方法:
session_set_save_handler(\OC::$server->getRedisSession(),true);register_shutdown_function('session_write_close');session_start();
也就是在session_start()方法之前調用,相當於告訴session儲存位置變成redis儲存,至此,以後使用的所有$_SESSION方法儲存的資料都會自動放到redis中去,而儲存用的key值就是session_id().
三、解釋:

\OC::$server->getRedisSession()

以上的調用對象的方法時使用了pimple容器儲存物件並調用的方式。具體如下使用:

namespace OC;
class Server extends SimpleContainer implements IServerContainer {

在此server類中註冊加入對象,

$this->registerService('RedisSession',function (Server $c) {   return new \OC\Session\redisSession(      $c->getSystemConfig()->getValue('redis')   );});
擷取對象方式:

/** * 新增的擷取使用者redissession的方法 */public function getRedisSession() {   return $this->query('RedisSession');}
其實也就是
session_set_save_handler(\OC::$server->getRedisSession(),true);中的
\OC::$server->getRedisSession()

就是上面一、中的類的對象

參考:http://www.tuicool.com/articles/yeeyume

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.