【问题标题】:browser caching or disk caching?浏览器缓存还是磁盘缓存?
【发布时间】:2011-08-13 15:31:34
【问题描述】:

就在几天前,我开始使用浏览器缓存,缓存 js 和 css 文件并保持“未修改”,效果很好。

现在我想在系统的许多页面上应用相同的方式。例如,我有这个页面列出了数据库中的“用户”,我想缓存该页面,以免查询使数据库过载。

我的问题是:这是否是一个好方法(缓存时页面是否仍然执行 db 查询?)还是应该转向磁盘缓存或 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 

【问题讨论】:

  • 不建议在动态页面上缓存(原因很明显)。
  • 在我正在使用的系统上,取消缓存并从数据库中调用结果取决于另一个因素。所以我可以保持缓存并在需要时取消它。

标签: php caching memcached


【解决方案1】:

一个简单的磁盘缓存示例,我在缓存经常变化的动态内容时使用了这种方法,例如统计信息、菜单、rssfeed、页面等。

<?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;
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2011-10-16
    • 1970-01-01
    • 2014-04-12
    相关资源
    最近更新 更多