我现在有一个相当复杂的index.php
,我想每小时只运行一次。实现这一目标的最佳方法是什么?我的一些想法
- 将它放在 APC 中
apc_store($page, 60*60*)
- 我觉得这不是 APC 的用途,并且可能会对我网站的其他部分造成不利影响 - 将输出保存到某个文件系统 - 然后 apache 需要在某个地方进行写访问,这可能会很痛苦
- 不知何故设置 apache 为我做缓存 - 这可能吗?
当下一个访问者来时,首先查找保存的文件,如果存在,则提供该文件,而不是执行 index.php 文件中的所有代码。一个基本的例子是
if (file_exists($cacheFileName))
{
require $cacheFileName;
exit;
}
// here goes the rest of your index.php code
//..
// assuming your output is buffered and is contained in $output:
echo $output;
$cacheFileName = '/path/to/your/file.inc';
file_put_contents($cacheFileName, $output);
设置一个 cron 作业,该作业将每小时或根据需要经常从磁盘中删除您保存的缓存文件。或者,在您的 index.php 中,在每个页面命中检查缓存文件是多久之前创建的,如果它的存在时间比您希望的要长,则生成一个新的缓存文件。不过,cron 作业更容易设置。
但是,要回答深刻的哲学问题,如果您不想依赖第三方缓存解决方案,将生成的输出保存到磁盘中的单独文件可能是最好的方法。APC 非常适合缓存将在需要时重新生成页面的代码,如果我们谈论的是小型(ish)应用程序,memcached 绝对是矫枉过正。
提供静态页面始终是最优化的方式。因此,例如使用 Cron 或您选择的任何其他计划服务,每小时生成一次索引的静态版本,并将其写入文件,例如 index.html。如果您仍然需要索引上的一些动态部分,您甚至可以让它生成为 .php。
我会说这绝对是最好的方法。当然,处理文件的 chmod 设置会有些小麻烦,但这并不是什么大问题。
我对 Rowlf 和 jamietelin 的回答略有不同。
创建3个文件:
索引.html
<meta http-equiv="refresh" content="0;url=/index_update.php" />
索引.php
<?php // do all your normal stuff ?>
index_update.php
<?php
$file = "index.html";
$time = 60 * 10 - (time() - filemtime($file));
# this is on the first install
if (filemtime($file) != filectime($file))
$time = 0;
if ($time > 0) {
die("Data was already updated in the 10 minutes. Please wait another " . ($time) . " seconds.");
}
ob_start();
require "index.php";
$data = ob_get_contents();
$fp = fopen($file, "w");
fwrite($fp, $data);
fclose($fp);
header("Location: /");
然后是一个 cronjob:
*/15 * * * * curl http://example.com/index_update.php
因此,如果有人在生产推送后偶然发现该页面,他们将透明地为您创建一个新的 index.html,否则,您的 cronjob 将每 15 分钟创建一次。
只需确保index.html可被您的 apache 服务器写入。如果这听起来很可怕,那么只需让您的 cronjob以另一个对index.htmlphp index_update.php
具有写入权限的用户身份运行。不过,您将无法访问所有 apache 环境。
希望对您有所帮助,欢迎评论。
另一个不错的选择是设置Squid Cache Server。
将页面保存到静态文件中并使用 .htaccess 规则来提供静态页面。
我不确定确切的细节,但我认为drupal 的codeignitor 和boost 可以做到这一点。