使用redis存储session

  1. 设置参数 session.save_handler、session.save_path 实现
  2. 通过继承SessionHandlerInterface接口,实现使用redis存储session

第一种实现方便、第二种实现灵活

修改php.ini配置

修改php.ini

session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"

Apache 环境

sudo service apache2 restart

Nginx 环境

sudo service php5-fpm restart

继承接口

SessionHandlerInterface 接口

php官网文档

1
2
3
4
5
6
7
8
9
SessionHandlerInterface {
/* 方法 */
abstract public bool close ( void )
abstract public bool destroy ( string $session_id )
abstract public bool gc ( int $maxlifetime )
abstract public bool open ( string $save_path , string $name )
abstract public string read ( string $session_id )
abstract public bool write ( string $session_id , string $session_data )
}

RedisSessionHandler类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class RedisSessionHandler implements SessionHandlerInterface
{
public $ttl = 1800;
protected $db;
protected $prefix;

public function __construct(\Redis $db, $prefix = 'PHPSESSID:')
{
$this->db = $db;
$this->prefix = $prefix;
}

public function write($session_id, $session_data)
{
$session_id = $this->prefix . $session_id;
$this->db->set($session_id, $session_data);
$this->db->expire($session_id, $this->ttl);
}

public function read($session_id)
{
$session_id = $this->prefix . $session_id;
$session_data = $this->db->get($session_id);
$this->db->expire($session_id, $this->ttl);
return $session_data;
}

public function close()
{
$this->db = null;
unset($this->db);
}

public function destroy($session_id)
{
$this->db->del($this->prefix . $session_id);
}

public function gc($maxlifetime)
{
// no action necessary because using EXPIRE
}

public function open($save_path, $session_id)
{
// No action necessary because connection is injected
// in constructor and arguments are not applicable.
}
}

/**
* redis 单例模式
*/
class RedisSingleton extends Redis
{
protected static $_instance = null;

public function getInstance()
{
if (null == self::$_instance)
{
self::$_instance = new self();
$host = '127.0.0.1';
$port = 6379;
// $host = $_SERVER['REDIS_HOST'];
// $port = $_SERVER['REDIS_PORT'];
self::$_instance->connect($host, $port);
}

return self::$_instance;
}
}

实例

1
2
3
4
5
6

$redis = RedisSingleton::getInstance();
$sessionHandler = new RedisSessionHandler($redis);

session_set_save_handler($sessionHandler);
session_start();
坚持原创技术分享,您的支持将鼓励我继续创作!