2011-08-13 77 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; 
} 
?>