php redis 存储实践,php利用redis实现session存储

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值