我正在尝试缓存静态内容,我希望该内容的生命周期为一小时,并且该内容是公开的,对每个人都相同。
我的 Controller 中有以下代码:
$response = new Response();
$response->setPublic();
$response->setMaxAge(3600);
$response->setSharedMaxAge(3600);
if ($response->isNotModified($request)) {
return $response;
}
return $this->render(
'ThemesBundle:Ad:content.html.twig',
array('context' => $context, 'block' => $block),
$response
);
但是 isNotModified()
函数始终返回 false。
PS:我使用的是 Symfony 2.0.22
最佳答案
你犯了一个错误,$response->isNotModified($request)
仅在使用缓存时使用 validation与 ETag或 Last-Modified测试!
在这里,您想使用 expiration 方法(使用 Cache-Control 或 Expires )。
所以只需删除这些行:
if ($response->isNotModified($request)) {
return $response;
}
$response->setMaxAge(3600);
(和 setSharedMaxAge
) 单独完成这项工作,您不需要测试任何东西,框架(或客户端navigator)将为您完成。
将在 3600 秒内提供相同的响应,而不会跳过该操作。 3600秒后,用户将重新通过该操作,并且该操作将被缓存3600秒,依此类推。
此外,您可以使用@Cache简化阅读的注释;)
关于caching - 使用 maxage header 时不可能出现 304 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17107098/