當前位置:才華齋>計算機>php語言>

php實現Session儲存到Redis

php語言 閱讀(2.62W)

介紹了php實現Session儲存到Redis的方法,php Session可以儲存到文字或者記憶體、還有資料庫,本文講的是存到Redis的方法.

php實現Session儲存到Redis

對於大訪問量的站點使用預設的Session 並不合適,我們可以將其存入資料庫、或者使用Redis KEY-VALUE資料儲存方案

  首先新建一個session表

CREATE TABLE `sessions` (

`sid` char(40) NOT NULL,

`updatetime` int(20) NOT NULL,

`data` varchar(200) NOT NULL,

UNIQUE KEY `sid` (`sid`) USING HASH

) ENGINE=MEMORY DEFAULT CHARSET=utf8;

Mysql 的memory引擎採用記憶體表,所有資料儲存在記憶體,操作速度快

<?php

//引入資料庫檔案

include "";

class MySessionHandler implements SessionHandlerInterface

{

private $savePath;

private $sessData;

public $expiretime; //設定過期時間

public $db; //資料庫

public function __construct($hanlder =''){

$this->db = Database::getInstance();

//獲取資料庫實力

///var_dump($this->db);

}

public function open($savePath, $sessionName)

{

return true;

}

public function close()

{

return true;

}

public function read($id)

{

$sql ="select * from sessions where sid ='$id'";

$result = $this->db->execute($sql);

if(!empty($result)){

return $this->sessData = $result;

}

}

//函式的.引數 $id -> 當前會話ID

//資料DATA -> 序列化之後的字串

public function write($id, $data)

{

// echo $id;

// echo $data;

$now = time();

$newExp = $now+$this->expiretime; //總時間=當前時間 + 期限時間

$sql = "select * from sessions where sid ='$id'";

$result = $this->db->getOne($sql);

//var_dump($result);

if($data==''||isset($data)){

$data = $this->sessData;

}

if($result){

//如果存在則更新

$sql ="update sessions set updatetime = '$newExp',data ='$data' where sid = '$id'";

//echo $sql;

$update_data =$this->db->execute($sql);

if($update_data){

return true;

}

}else{

//不存在則生成生成

$sql = "insert into sessions(sid,updatetime,data) values('$id','$now','$data')";

$insert_data = $this->db->execute($sql);

if($insert_data){

return true;

}

}

return false;

}

public function destroy($id)

{ //銷燬

$sql = "delete from sessions where sid="."$id";

$destory = $this->db->execute($sql);

if($destory){

return true;

}else{

return false;

}

}

public function gc($sessMaxLifeTime)

{

$t = time();

$sql ="delete from sessions where $t - 'updatetime'>${sessMaxLifeTime}";

$data = $this->db->execute($this->tosql);

if($data){