用php开发网站,一般都要尽量避免数据库查询以减少服务器压力,可随着网站内容增多,访问量上升,服务器还是不堪重负。直接生成静态页面是一个办法,可页面越来越多的时候,管理起来非常困难。更好的解决办法就是用缓存,首次访问的时候先检查是否已经缓存和缓存是否过期,有则直接返回,没有或者过期才去数据库查询,处理后返回html。这种机制真是个好主意,可代码应该怎么写呢? 别担心,github上面已经有人写好了,超级好用,快试试吧,源码如下:
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;
}
}
}
网站首页入口处:
include_once("class.cache.php");
$cache = new Cache;
$cache->start();
最后:
$cache->end();