Rails 3.1 和 Http 页面缓存

发布于 2024-12-16 19:03:20 字数 667 浏览 4 评论 0原文

鉴于 Heroku Cedar 没有 Varnish 提供的 http 缓存,我想使用 Rack::Cache。 我被告知 Rails 3.1.1 默认情况下有 Rack::Cache 处于活动状态,我只需要确保配置中有:

config.action_controller.perform_caching = true

并且我需要选择一个缓存存储,对于这个实验我正在使用:

config.cache_store = :memory_store

在我想要缓存的页面的操作中,我添加了以下几行:

response.header['Cache-Control'] = 'public, max-age=300'
response.header['Expires'] = CGI.rfc1123_date(Time.now + 300)

此代码用于与 Varnish 配合良好,第一个请求将返回 200,后续(5 分钟)将返回304

Rails 3.1 和 Heroku Cedar Stack 不会发生这种情况。 我确实在响应中得到了这些标头,但后续请求返回 200 而不是 304。

我做错了什么?谢谢。

Given that Heroku Cedar doesn't have http caching provided by Varnish I would like to use Rack::Cache.
I have been told that rails 3.1.1 have Rack::Cache active by default, I just need to make sure to have in the configuration:

config.action_controller.perform_caching = true

and I need to pick a cache store, for this experiment I'm using:

config.cache_store = :memory_store

In the action of the page I want to cache I've added the following lines:

response.header['Cache-Control'] = 'public, max-age=300'
response.header['Expires'] = CGI.rfc1123_date(Time.now + 300)

This code used to work fine with Varnish, the first request would return a 200 and the subsequent (for 5 mins) would return a 304.

This doesn't happen with Rails 3.1 and Heroku Cedar Stack.
I do get those headers in the response but subsequent requests returns 200 instead of 304.

What am I doing wrong? Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有心的人 2024-12-23 19:03:20

正如您所指出的,Cedar 堆栈不使用 Varnish。这意味着 Web 请求将始终到达 ruby​​ 服务器。

考虑到这一点,Rack::Cache 将尊重您的标头并提供缓存的内容。

但是,由于请求实际上是通过 http 层进入 Rails 应用程序,因此响应将始终为 200,因为缓存不再发生在 http 层。

要确认这是真的,请将其插入到您的缓存操作之一中:

<%= Time.now.to_i %>

然后,重新加载页面几次,您会发现时间戳消失了改变。

As you noted, the Cedar stack doesn't use Varnish. That means a web request will always hit the ruby server.

With that in mind, Rack::Cache will respect your headers and serve the cached content.

However, since the request is actually going past the http layer into the rails app, the response will always be 200 since the cache doesn't happen at the http layer anymore.

To confirm this is true, insert this in one of your cached actions:

<%= Time.now.to_i %>

Then, reload the page several times and you'll notice the timestamp won't change.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文