php实现Session存储到Redis

这篇文章主要介绍了php实现Session存储到Redis的方法,php Session可以保存到文本或者内存、还有数据库,本文讲的是存到Redis的方法。

对于大访问量的站点使用默认的Session 并不合适,我们可以将其存入数据库、或者使用Redis KEY-VALUE数据存储方案

首先新建一个session表

  1. CREATE TABLE `sessions` (
  2. `sid` char(40) NOT NULL,
  3. `updatetime` int(20) NOT NULL,
  4. `data` varchar(200) NOT NULL,
  5. UNIQUE KEY `sid` (`sid`) USING HASH
  6. ) ENGINE=MEMORY DEFAULT CHARSET=utf8;

Mysql 的memory引擎采用内存表,所有数据存储在内存,操作速度快

  1. <?php
  2. //引入数据库文件
  3. include "db.php";
  4. class MySessionHandler implements SessionHandlerInterface
  5. {
  6. private $savePath;
  7. private $sessData;
  8. public $expiretime; //设置过期时间
  9. public $db; //数据库
  10. public function __construct($hanlder =''){
  11. $this->db = Database::getInstance();
  12. //获取数据库实力
  13. ///var_dump($this->db);
  14. }
  15. public function open($savePath, $sessionName)
  16. {
  17. return true;
  18. }
  19. public function close()
  20. {
  21. return true;
  22. }
  23. public function read($id)
  24. {
  25. $sql ="select * from sessions where sid ='$id'";
  26. $result = $this->db->execute($sql);
  27. if(!emptyempty($result)){
  28. return $this->sessData = $result;
  29. }
  30. }
  31. //函数的参数 $id -> 当前会话ID
  32. //数据DATA -> 序列化之后的字符串
  33. public function write($id, $data)
  34. {
  35. // echo $id;
  36. // echo $data;
  37. $now = time();
  38. $newExp = $now+$this->expiretime; //总时间=当前时间 + 期限时间
  39. $sql = "select * from sessions where sid ='$id'";
  40. $result = $this->db->getOne($sql);
  41. //var_dump($result);
  42. if($data==''||isset($data)){
  43. $data = $this->sessData;
  44. }
  45. if($result){
  46. //如果存在则更新
  47. $sql ="update sessions set updatetime = '$newExp',data ='$data' where sid = '$id'";
  48. //echo $sql;
  49. $update_data =$this->db->execute($sql);
  50. if($update_data){
  51. return true;
  52. }
  53. }else{
  54. //不存在则生成生成
  55. $sql = "insert into sessions(sid,updatetime,data) values('$id','$now','$data')";
  56. $insert_data = $this->db->execute($sql);
  57. if($insert_data){
  58. return true;
  59. }
  60. }
  61. return false;
  62. }
  63. public function destroy($id)
  64. { //销毁
  65. $sql = "delete from sessions where s$id";
  66. $destory = $this->db->execute($sql);
  67. if($destory){
  68. return true;
  69. }else{
  70. return false;
  71. }
  72. }
  73. public function gc($sessMaxLifeTime)
  74. {
  75. $t = time();
  76. $sql ="delete from sessions where $t - 'updatetime'>${sessMaxLifeTime}";
  77. $data = $this->db->execute($this->tosql);
  78. if($data){
  79. return true;
  80. }else{
  81. return false;
  82. }
  83. return true;
  84. }
  85. }

实例化

此处 PHP 手册可以有两种方法

1,实现了SessionHandlerInterface借口的对象,自PHP5.4可以使用

2 ,直接使用 session_set_save_handler

  1. //判断PHP版本
  2. if(version_compare(PHP_VERSION,5.4)==1){
  3. session_set_save_handler($handler, true);
  4. session_start();
  5. }else{
  6. ini_set('session.use_trans_sid',0);
  7. ini_set('session.use_cookies',1);
  8. ini_set('session.cookie_path','/');
  9. ini_set('session.save_handler','user');
  10. session_module_name('user');
  11. session_set_save_handler(array($session,"open"),array($session,"close"),array($session,"read"),array($session,"write"),array($session,"destory"),array($session,"gc"));
  12. session_start();
  13. }
  14. $_SESSION['QQ']="QQ";
  15. echo $_SESSION['QQ'];

数据库代码

  1. <?php
  2. class Database{
  3. static $instance;
  4. static $db;
  5. static function getInstance(){
  6. if(self::$instance){
  7. return self::$instance;
  8. }else{
  9. return new Database();
  10. }
  11. }
  12. public function __construct(){
  13. self::$db = new PDO('mysql:host=localhost;dbname=session', 'root','');
  14. }
  15. public function getOne($sql){
  16. $rs =self::$db->query($sql);
  17. @$rs->setFetchMode(PDO::FETCH_ASSOC);//返回关联数组
  18. $result = $rs -> fetch();
  19. return $result;
  20. }
  21. public function execute($sql){
  22. $rs = self::$db->exec($sql);
  23. return $rs;
  24. }
  25. }
  26. //$data = Database::getInstance();
  27. //var_dump($data);

使用REDIS 存储SESSION

  1. <?php
  2. class SessionManager{
  3. private $redis;
  4. private $sessionSavePath;
  5. private $sessionName;
  6. private $sessionExpireTime = 30;
  7. public function __construct(){
  8. $this->redis = new Redis();
  9. $this->redis->connect('127.0.0.1',6379); //连接redis
  10. $retval = session_set_save_handler(
  11. array($this,"open"),
  12. array($this,"close"),
  13. array($this,"read"),
  14. array($this,"write"),
  15. array($this,"destory"),
  16. array($this,"gc")
  17. );
  18. session_start();
  19. }
  20. public function open($path,$name){
  21. return true;
  22. }
  23. public function close(){
  24. return true;
  25. }
  26. public function read($id){
  27. $value = $this->redis->get($id);
  28. if($value){
  29. return $value;
  30. }else{
  31. return "";
  32. }
  33. }
  34. public function write($id,$data){
  35. if($this->redis->set($id,$data)){
  36. $this->redis->expire($id,$this->sessionExpireTime);
  37. //设置过期时间
  38. return true;
  39. }
  40. return false;
  41. }
  42. public function destory($id){
  43. if($this->redis->delete($id)){
  44. return true;
  45. }
  46. return false;
  47. }
  48. public function gc($maxlifetime){
  49. return true;
  50. }
  51. //析构函数
  52. public function __destruct(){
  53. session_write_close();
  54. }
  55. }
  56. $re = new SessionManager();
  57. $_SESSION['name'] = "qq";
  58. echo $_SESSION['name'];
以上就是详细的介绍了php实现Session存储到Redis的方法,希望对大家的学习有所帮助。