1

如何使 PHP 脚本缓存对我们的私有反向代理 (Squid) 友好?

我希望它在一天的剩余时间内保持缓存。换句话说,页面的最后一次修改是今天00:00,它将在明天00:00过期。

可靠地执行此操作所需的最低 HTTP 标头是多少?

编辑:我不希望客户端的浏览器缓存有任何不同。也就是说,我希望在任何给定时间保留对清除 Squid 服务器上过时页面的控制权。

4

4 回答 4

3

@OP:下面是一些注释代码来实现您的要求。

@cletus:您说 memcached 是 OP 想要的,而这不是 Squid 的设计目的。

我不知道 Squid 的设计目的是什么,但我知道它用途,而且肯定有人使用它作为反向代理来减轻动态页面生成的负担。除了标准的 HTTP 标头外,不需要“绑定”。

我不确定您为什么在不了解应用程序和环境的性质的情况下如此迅速地推荐 memcached。

<?php

// the time we got hit and generated content
$now = time();
$generatedAt = gmdate('D, d M Y H:i:s T', $now);

// the last modified date (midnight on the same day of generation, as
// per your business-rule)
$lastModified = gmdate('D, d M Y 00:00:00 T', $now);

// date of expiry (24 hours after the last modified date, as per your
// business-rule)
$expiresAt = gmdate('D, d M Y H:i:s T', strtotime($lastModified) + 86400);

// the minimum required http headers to make Squid do what you asked is
// Last-modified and Cache-control.  We need to give Cache-control the
// expiry time in terms of "age" (in seconds) so we calculate that below.
// Optionally you could also provide the "Expires: $expiresAt" header to
// tell the browser/client the same information, just in a different way.
// This is not required for Squid though.
$maxAge = strtotime($expiresAt) - strtotime($generatedAt);
header('Last-modified: ' . $lastModified);
header('Cache-control: max-age=' . $maxAge);

// The rest is simply informational
header('Content-type: text/plain');
echo "The content of this page was last modified at $lastModified\n";
echo "This page was generated at $generatedAt and will be cached by Squid for $maxAge seconds until $expiresAt\n";

// Sample output:
//
// The content of this page was last modified at Tue, 13 Jan 2009 00:00:00 GMT
// This page was generated at Tue, 13 Jan 2009 04:29:33 GMT and will be cached by Squid for 70227 seconds until Wed, 14 Jan 2009 00:00:00 GMT
于 2009-01-13T04:30:28.353 回答
1

我假设您的意思是要缓存脚本的输出,而不是脚本本身。而且您显然想要服务器端脚本,因此 HTTP 标头不是您想要的(除非有一些与 Squid 相关的东西,这很可能是)。但这不是 Squid 的设计目的。

对于这种事情,你真的想要memcached(或类似的)。

检查结果是否在缓存中。如果是,请将其退回。如果不是,则生成结果(例如使用 ob_start() 等),将其放入缓存中并返回。

于 2009-01-13T02:27:22.957 回答
1

您可以运行脚本并生成要提供的静态 HTML 文件。这样,何时替换内容由您决定。

您不必在 Web 服务器中运行脚本。一个 cron 工作完美地工作。

于 2009-01-13T03:19:36.017 回答
0

你试过使用 APC 吗?

http://us.php.net/apc

Alternative PHP Cache (APC) 是一个免费且开放的 PHP 操作码缓存。它旨在为缓存和优化 PHP 中间代码提供一个免费、开放和健壮的框架。

于 2009-03-23T15:17:09.687 回答