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'];
