php用redis存储session数据(附一个简单的类)

在php.ini中配置

session.save_handler = Redis

session.save_path = "tcp://localhost:6379"

或者在php文件中配置的,

ini_set('session.save_handler','Redis');

ini_set('session.save_path','tcp://localhost:6379');

<?php
class RedisSession{

private $redis;

private $sessionSavePath;

private $sessionName;

private $sessionExpireTime=30;

public function CONSTRUCT(){

$this->redis = new Redis();

$this->redis->connect('127.0.0.1',6379);

$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);

if($value){

return $value;

}else{

return '';

}

}

public function write($id,$data){

if($this->redis->set($id,$data)){

$this->redis->expire($id,$this->sessionExpireTime);

return true;

}

return false;

}

public function destroy($id){

if($this->redis->delete($id)){

return true;

}

return false;

}

public function gc($maxlifetime){

return true;

}

public function DESTRUCT(){

session_write_close();

}

}

?>

在新建两个文件,test1.php

<?php

include('RedisSession.php');

new RedisSession();

$_SESSION['name'] = 'xingdong';

?>

test2.php

<?php

include('RedisSession.php');

new RedisSession();

echo $_SESSION['name'];

?>