您的位置:首页 > 数据库 > Redis

thinkphp使用redis存储session

2016-04-28 17:10 841 查看
1、

      session(array('type'=>
'Redis'));

      session_start();

      注意要在session开启之前做好改存redis配置,(*thinkphp有个自动开启session的配置SESSION_AUTO_START要改为false)



2、在session扩展类中加入Redis.class.php文件



Redis.class.php的代码为:

<?php

namespace Think\Session\Driver;

class Redis {

// Redis连接对象

protected $redis;

// Session过期时间

protected $expire;

/**

* 打开方法

* @param type $path

* @param type $name

* @return type

*/

public function open($path, $name) {

$this->expire = C('SESSION_EXPIRE') ? C('SESSION_EXPIRE') : ini_get('session.gc_maxLifetime');

//$this->expire = 0;

/*$this->redis = new \Redis();

return $this->redis->connect(C('REDIS_SERVER'), C('REDIS_PORT'));*/

return $this->redis = \Think\Redis::getRedis();

}

/**

* 关闭

* @return type

*/

public function close() {

$this->gc(ini_get('session.gc_maxlifetime'));

return $this->redis->close();

}

/**

* 读取

* @param string $id

* @return type

*/

public function read($id) {

$id = C('SESSION_PREFIX') . $id;

$data = $this->redis->get($id);

//print_r($id);

return $data ? $data : '';

}

/**

* 写入

* @param string $id

* @param type $data

* @return type

*/

public function write($id, $data) {

$id = C('SESSION_PREFIX') . $id;

//print_r($data);

return $this->redis->set($id, $data, $this->expire);

}

/**

* 销毁

* @param string $id

*/

public function destroy($id) {

$id = C('SESSION_PREFIX') . $id;

$this->redis->delete($id);

}

/**

* 垃圾回收

* @param type $maxLifeTime

* @return boolean

*/

public function gc($maxLifeTime) {

return true;

}

}

代码中redis链接$this->redis = \Think\Redis::getRedis();是额外编写的单例类(Think/Redis.class.php)

redis单例类:

<?php

namespace Think;

/**

* ThinkPHP REDIS 单例类

*/

class Redis {

private static $_instance = null;

private function __construct(){

self::$_instance = new \Redis();

$config = C("REDIS");

self::$_instance->connect($config['host'],$config['port']);

if(isset($config['password'])){

self::$_instance->auth($config['password']);

}

}

public static function getRedis(){

if(!self::$_instance){

new self;

}

return self::$_instance;

}

/*

* 禁止clone

*/

private function __clone(){}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: