PHP中Redis替代檔案儲存體Session

來源:互聯網
上載者:User

PHP預設使用檔案儲存體session,如果並發量大,效率非常低。而Redis對高並發的支援非常好,所以,可以使用redis替代檔案儲存體session。

這裡,介紹下php的session_set_save_handler 函數的作用和使用方法。該函數定義使用者級session儲存函數(如開啟、關閉、寫入等)。原型如下:

bool session_set_save_hanler(callback open,callback close,callback read,callback write,callback destory,callback gc)

session_set_save_handler 函數各參數作用如下表

參 數 描述
open 當session開啟時調用此函數。接收兩個參數,第一個參數是保持session的路徑,第二個參數是session的名字
close 當session操作完成時調用此函數。不接收參數。
read 以session ID作為參數。通過session ID從資料存放區方中取得資料,並返回此資料。如果資料為空白,可以返回一個Null 字元串。此函數在調用session_start 前被觸發
write 當資料存放區時調用。有兩個參數,一個是session ID,另外一個是session的資料
destroy 當調用session_destroy 函數時觸發destroy函數。只有一個參數 session ID
gc 當php執行session記憶體回收機制時觸發

在使用該函數前,先把php.ini設定檔的session.save_handler選項設定為user,否則session_set_save_handle 不會生效。

編寫一個session管理類sessionManager.php ,代碼如下:

<?phpclass SessionManager{    private $redis;    private $sessionSavePath;    private $sessionName;    private $sessionExpireTime=30;//redis,session的到期時間為30s    public function __construct(){        $this->redis = new Redis();//建立phpredis執行個體        $this->redis->connect('127.0.0.1',6379);//串連redis        $this->redis->auth("107lab");//授權        $retval = session_set_save_handler(            array($this,"open"),            array($this,"close"),            array($this,"read"),            array($this,"write"),            array($this,"destroy"),            array($this,"gc")        );        session_start();    }    public function open($path,$name){        return true;    }    public function close(){        return true;    }    public function read($id){        $value = $this->redis->get($id);//擷取redis中的指定記錄        if($value){            return $value;        }else{            return '';        }    }    public function write($id,$data){        if($this->redis->set($id,$data)){//以session ID為鍵,儲存            $this->redis->expire($id,$this->sessionExpireTime);//設定redis中資料的到期時間,即session的到期時間            return true;        }        return false;    }    public function destroy($id){        if($this->redis->delete($id)){//刪除redis中的指定記錄            return true;        }        return false;    }    public function gc($maxlifetime){        return true;    }    public function __destruct(){        session_write_close();    }}

SessionManager建構函式主要用來串連Redis伺服器,使用session_set_save_handler函數設定session回呼函數,並調用session_start函數開啟session功能。因為本例中open、close和gc回呼函數的作用不是很大,所以直接返回true。

在write回呼函數中,以session ID 作為key,把session的資料作為value儲存到redis伺服器,設定session的到期時間為30秒。在read 回調函中,以session ID 作為key從redis伺服器中讀取資料,並返回此資料。而在destroy回呼函數重,則以session ID 作為key 從redis伺服器中刪除對應的session資料。

使用時,只需包含SessionManager類,然後執行個體化一個SessionManager對象。下面建立個session_set.php檔案。輸入代碼

<?php    include('SessionManager.php');    new SessionManager();    $_SESSION['username'] = 'captain';

然後再建立一個session_get.php檔案,輸入如下代碼:

<?php    include('SessionManager.php');    new SessionManager();    echo $_SESSION['username'];

測試時,首先訪問session_set.php,然後再訪問 session_get.php,輸出結果如下所示:

再查看redis資料庫,如下所示

127.0.0.1:6379> keys *1) "oe94eic337slnjv1bvlreoa574"127.0.0.1:6379> get oe94eic337slnjv1bvlreoa574"username|s:7:\"captain\";"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.