2011-08-13 74 views
0

就在幾天前,我開始使用瀏覽器緩存來緩存js和css文件,並將其保留爲「未修改」,並且效果非常好。瀏覽器緩存或磁盤緩存?

現在我想在系統的許多頁面上應用相同的方式。例如,我有這個頁面列出數據庫中的「用戶」,並且我想要緩存頁面不要用查詢過載數據庫。

我的問題是:即使是一個很好的方法(頁面仍然執行數據庫查詢時緩存嗎?)或者我應該轉向磁盤緩存或memcached?

header("HTTP/1.1 304 Not Modified"); 
header("Expires: ".gmdate("D, d M Y H:i:s", time()+(60*86400))." GMT"); 
header("Cache-Control: must-revalidate"); 
mysql_query(" SELECT * FROM `users` "); 
// list all users 
+1

緩存緩存動態含量的不同,當該方法(原因很明顯)。 –

+0

在我正在處理的系統上,取消緩存並從數據庫中調用結果取決於另一個因素。所以我可以保留它緩存並在需要時取消。 – Dewan159

回答

2

一個簡單的磁盤高速緩存例如,我已經使用了dosent變化常常像統計,菜單,rssfeeds,頁等..建議不要在動態網頁

<?php 
$cacheTime=3600; /*1hour*/ 

if(file_exists('./cache/'.sha1('users').'.php') && $_SESSION['user_status']!=true){ 
    $FileCreationTime = filectime('./cache/'.sha1('users').'.php'); 
    /* Calculate file age in seconds*/ 
    $FileAge = time() - $FileCreationTime; 
    /*1h cache*/ 
    if ($FileAge > ($cacheTime)){unlink('./cache/'.sha1('users').'.php');header('Location: '.$_SERVER['REQUEST_URI']);die();} 
    include("./cache/".sha1('users').".php"); 
    /*Cache is there and not older then 1hour so echo the cache*/ 
    echo base64_decode($cache); 
}else{ 
    /*************************************************************/ 
    //Cache is NOT there or user logged in or older then 1hour so regenerate content 

    //Do Content and store in $return variable 
    $return=''; 


    $result = mysql_query(" SELECT * FROM `users` "); 
    while($row=mysql_fetch_assoc($result)){ 
     $return .='<ul>'.$row['user'].'</ul>'; 
     ... 
    } 
    ... 
    ... 
    $return .='bla bla'; 
    /*************************************************************/ 

    /*Check if not logged in else save*/ 
    if($_SESSION['user_status']!=true){ 
     $cache_file_encoded = base64_encode($return); 
     $cache_file = <<<CACHE 
<?php 
/** 
* Cached for:Users Page [{$_SERVER["HTTP_HOST"]}{$_SERVER['REQUEST_URI']}] Base64 
*/ 
\$cache ="$cache_file_encoded"; ?> 
CACHE; 
     file_put_contents('./cache/'.sha1('users').'.php',$cache_file); 
} 
echo $return; 
} 
?>