PHP session文件獨占鎖引起阻塞問題解決方法
PHP默認的會話處理器是session.save_handler = files(即文件)。如果同一個客戶端同時并發(fā)發(fā)送多個請求(如ajax在頁面同時發(fā)送多個請求),且腳本執(zhí)行時間較長,就會導(dǎo)致session文件阻塞,影響性能。因為對于每個請求,PHP執(zhí)行session_start(),就會取得文件獨占鎖,只有在該請求處理結(jié)束后,才會釋放獨占鎖。這樣,同時多個請求就會引起阻塞。解決方案如下:
(1)修改會話變量后,立即使用session_write_close()來保存會話數(shù)據(jù)并釋放文件鎖。
session_start(); $_SESSION['test'] = 'test'; session_write_close(); //do something
(2)利用session_set_save_handler()函數(shù)是實現(xiàn)自定義會話處理。
function open($savePath, $sessionName)
{
echo 'open is called';
return true;
}
function close()
{
echo 'close is called';
return true;
}
function read($sessionId)
{
echo 'read is called';
return '';
}
function write($sessionId, $data)
{
echo 'write is called';
return true;
}
function destroy($sessionId)
{
echo 'destroy is called';
return true;
}
function gc($lifetime)
{
echo 'gc is called';
return true;
}
session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
register_shutdown_function ( 'session_write_close' );
session_start();
$_SESSION['foo'] = "bar";
當(dāng)然,在 php 5.4.0之后,你可以通過實現(xiàn) SessionHandlerInterface 接口或繼承 SessionHandler 類來使用。
class MySessionHandler extends SessionHandler {
public function __construct()
{
}
public function open($save_path, $session_id)
{
}
public function close()
{
}
public function create_sid()
{
}
public function read($id)
{
}
public function write($id, $data)
{
}
public function destroy($id)
{
}
}
$handler = new MySessionHandler();
//第2個參數(shù)將函數(shù) session_write_close() 注冊為 register_shutdown_function() 函數(shù)。
session_set_save_handler($handler, true);
你可以對上面的代碼進行具體實現(xiàn)和封裝,利用mysql或其它內(nèi)存數(shù)據(jù)庫來管理會話數(shù)據(jù)。還能解決使用集群
時,session數(shù)據(jù)共享問題。
相關(guān)文章
Zend Framework教程之分發(fā)器Zend_Controller_Dispatcher用法詳解
這篇文章主要介紹了Zend Framework教程之分發(fā)器Zend_Controller_Dispatcher用法,結(jié)合實例形式詳細分析了分發(fā)器Zend_Controller_Dispatcher的結(jié)構(gòu),功能,使用技巧與相關(guān)注意事項,需要的朋友可以參考下2016-03-03
thinkPHP實現(xiàn)的省市區(qū)三級聯(lián)動功能示例
這篇文章主要介紹了thinkPHP實現(xiàn)的省市區(qū)三級聯(lián)動功能,詳細分析了thinkPHP實現(xiàn)省市區(qū)三級聯(lián)動功能的詳細步驟與相關(guān)操作技巧,需要的朋友可以參考下2017-05-05
php each 返回數(shù)組中當(dāng)前的鍵值對并將數(shù)組指針向前移動一步實例
php each函數(shù)用于獲取數(shù)組的鍵值對,并將數(shù)組指針向前移動一步, each函數(shù)經(jīng)常和list結(jié)合使用來遍歷數(shù)組。本文章向大家介紹each的基本使用方法,需要的朋友可以參考下2016-11-11

