php把session存储在数据库性能如何啊?

SessionHandler.php文件内容如下
namespaceDry\Base;
classSessionHandler{
private$pdo=null;
private$lifeTime=1440;
publicfunction__construct($pdo)
{
$this->pdo=$pdo;
$this->lifeTime=get_cfg_var('session.gc_maxlifetime');
session_set_save_handler(
array($this,'open'),
array($this,'close'),
array($this,'read'),
array($this,'write'),
array($this,'destroy'),
array($this,'gc')
);
register_shutdown_function('session_write_close');
}
publicfunctionopen($save_path,$session_name)
{
returntrue;
}
publicfunctionclose()
{
returntrue;
}
publicfunctionread($session_id)
{
$time=date('Y-m-dH:i:s');
$sql="selectsession_datafromsession_handlerwheresession_id='{$session_id}'andsession_expires>'{$time}'limit1";
$sm=$this->pdo->prepare($sql);
$sm->execute();
if($sm->rowCount()){
$result=$sm->fetch();
return$result['session_data'];
}
else{
return'';
}
}
publicfunctionwrite($session_id,$session_data)
{
$time=date('Y-m-dH:i:s',time()+$this->lifeTime);
$sql="selectcount(1)astotalfromsession_handlerwheresession_id='{$session_id}'limit1";
$sm=$this->pdo->prepare($sql);
$sm->execute();
if($sm->fetchColumn()){
$sql="updatesession_handlersetsession_data='{$session_data}',session_expires='{$time}'wheresession_id='{$session_id}'";
}
else{
$sql="insertintosession_handler(session_id,session_data,session_expires)values('{$session_id}','{$session_data}','{$time}')";
}
$sm=$this->pdo->prepare($sql);
$sm->execute();
returntrue;
}
publicfunctiondestroy($session_id)
{
$sql="deletefromsession_handlerwheresession_id='{$session_id}'";
$sm=$this->pdo->prepare($sql);
$sm->execute();
returntrue;
}
publicfunctiongc($maxlifetime)
{
$time=date('Y-m-dH:i:s',time()-$maxlifetime);
$sql="deletefromsession_handlerwheresession_expires<'{$time}'";
$sm=$this->pdo->prepare($sql);
$sm->execute();
returntrue;
}
}
?>
test.php文件内容如下
require_once('SessionHandler.php');
useDry\Base\SessionHandler;
$pdo=newPDO('mysql:host=192.168.1.20;dbname=test;port=3306','root','1234',array(
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT=>false,
PDO::MYSQL_ATTR_INIT_COMMAND=>'setnamesutf8',
PDO::ATTR_ORACLE_NULLS=>PDO::NULL_TO_STRING,
PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC
));
newSessionHandler($pdo);
session_start();
$_SESSION['name']='test';
echo$_SESSION['name'];
?>
session_handler表结构如下
CREATETABLE`session_handler`(
`id`bigint(20)unsignedNOTNULLAUTO_INCREMENT,
`session_id`varchar(64)NOTNULL,
`session_data`mediumtext,
`session_expires`datetimeNOTNULL,
PRIMARYKEY(`id`),
UNIQUEKEY`session_id`(`session_id`)USINGBTREE
)ENGINE=InnoDBAUTO_INCREMENT=1DEFAULTCHARSET=utf8;
鸿蒙传说
浏览 679回答 2
2回答

叮当猫咪

不推荐存数据库中,假如站点访问量大的时候,对数据库会频繁写入,频繁读取,从而影响数据库性能。一般用redismemcache存更好些。而且维护过期时间等也方便。设置key过期时间就好。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript