【发布时间】:2014-09-08 21:19:00
【问题描述】:
上周我在我的网站上推出了一个非常简单的缓存系统,使用我的网站模板文件中引用的 PHP 类。缓存系统显着提高了服务器响应时间(模板从我们数据中心的其他几个服务器中提取数据,因此 Apache 不会全部缓存在内存中)。问题是,它是过度缓存文件。我相信我已将它设置为缓存五分钟,或者直到 HTML 被修改,但它仍在缓存版本创建后的几天内提供页面的缓存版本。
谁能发现我的代码有任何问题,或者您是否知道任何版本的 PHP/Apache/Red Hat 可能会报告文件修改时间的错误信息? (我们使用的是 PHP 5.3.3、Apache 2.2.15 和 RHEL 6。我一直在运行 mod_pagespeed,但即使我禁用了它,问题仍然存在。)
<?php
class IWU_Cache {
protected $cache_prefix = '/tmp/webcache_';
protected $remote_delay = 300; // in seconds; 300 is five minutes
protected $path;
public function __construct($path = '') {
$this->path = $path;
}
public function isRecentlyCached() {
$cache_location = $this->path2Cache($this->path);
if(is_file($cache_location)) {
if(is_file($_SERVER['DOCUMENT_ROOT'] . $this->path) && (filemtime($_SERVER['DOCUMENT_ROOT'] . $this->path) < filemtime($cache_location))) {
return TRUE;
}
elseif(filemtime($cache_location) > time() - $this->remote_delay) {
return TRUE;
}
}
return FALSE;
}
public function getCachedVersion() {
return file_get_contents($this->path2Cache($this->path));
}
public function addToCache($html) {
return file_put_contents($this->path2Cache($this->path), $html);
}
protected function path2Cache($path) {
return $this->cache_prefix . str_replace('/', '____', $path);
}
}
?>
【问题讨论】:
-
您的缓存类是否比您发布的更多?
-
@w3d:不;就是这样。
-
与您的问题无关(很高兴您对其进行了排序),但我注意到您的课程存在一些查询/异常情况... 1. 中的
$path参数你的构造函数被声明为可选的,但它不是可选的——没有它你的类将无法运行,并且似乎没有任何其他方法可以设置它。 2. 您总是将$this->path(受保护的属性)传递给path2cache()(受保护的方法)——这似乎没有必要?