用php開發(fā)網(wǎng)站,一般都要盡量避免數(shù)據(jù)庫查詢以減少服務(wù)器壓力,可隨著網(wǎng)站內(nèi)容增多,訪問量上升,服務(wù)器還是不堪重負。直接生成靜態(tài)頁面是一個辦法,可頁面越來越多的時候,管理起來非常困難。更好的解決辦法就是用緩存,首次訪問的時候先檢查是否已經(jīng)緩存和緩存是否過期,有則直接返回,沒有或者過期才去數(shù)據(jù)庫查詢,處理后返回html。這種機制真是個好主意,可代碼應(yīng)該怎么寫呢? 別擔(dān)心,github上面已經(jīng)有人寫好了,超級好用,快試試吧,源碼如下:
class Cache {
// Pages you do not want to Cache:
var $doNotCache = array("admin"); // 不緩存的頁面
// General Config Vars
var $cacheDir = "cache";
var $cacheTime = 36000; // 緩存文件有效期
var $caching = false;
var $cacheFile;
var $cacheFileName;
var $cacheLogFile;
var $cacheLog;
function __construct(){
$this->cacheFile = base64_encode($_SERVER['REQUEST_URI']);
$this->cacheFileName = $this->cacheDir.'/'.$this->cacheFile.'.txt';
$this->cacheLogFile = $this->cacheDir."/log.txt";
if(!is_dir($this->cacheDir)) mkdir($this->cacheDir, 0755);
if(file_exists($this->cacheLogFile))
$this->cacheLog = unserialize(file_get_contents($this->cacheLogFile));
else
$this->cacheLog = array();
}
function start(){
$location = array_slice(explode('/',$_SERVER['REQUEST_URI']), 0);
if(!in_array($location[2],$this->doNotCache)){
if(file_exists($this->cacheFileName) && (time() - filemtime($this->cacheFileName)) < $this->cacheTime && $this->cacheLog[$this->cacheFile] == 1){
$this->caching = false;
echo file_get_contents($this->cacheFileName);
exit();
}else{
$this->caching = true;
ob_start();
}
}
}
function end(){
if($this->caching){
file_put_contents($this->cacheFileName,ob_get_contents());
ob_end_flush();
$this->cacheLog[$this->cacheFile] = 1;
if(file_put_contents($this->cacheLogFile,serialize($this->cacheLog)))
return true;
}
}
function purge($location){
$location = base64_encode($location);
$this->cacheLog[$location] = 0;
if(file_put_contents($this->cacheLogFile,serialize($this->cacheLog)))
return true;
else
return false;
}
function purge_all(){
if(file_exists($this->cacheLogFile)){
foreach($this->cacheLog as $key=>$value) $this->cacheLog[$key] = 0;
if(file_put_contents($this->cacheLogFile,serialize($this->cacheLog)))
return true;
else
return false;
}
}
}
網(wǎng)站首頁入口處:
include_once("class.cache.php");
$cache = new Cache;
$cache->start();
最后:
$cache->end();
