【发布时间】:2012-05-30 17:54:03
【问题描述】:
我这辈子都想不通。尝试使用 Rack::Cache 来缓存我在 Heroku 上的一些静态公共页面,除了做动作缓存以防它通过反向代理。
例如,这是我的“home”操作中的代码:
class StaticPagesController < ApplicationController
layout 'public'
caches_action :about, :contact, ......, :home, .....
......
def home
last_modified = File.mtime("#{Rails.root}/app/views/static_pages/home.html.haml")
fresh_when last_modified: last_modified , public: true, etag: last_modified
expires_in 10.seconds, :public => true
end
出于所有意图和目的,这应该有一个 max-age 10 no 的公共缓存控制标签?
$ curl -I http://myapp-staging.herokuapp.com/
HTTP/1.1 200 OK
Cache-Control: max-age=0, private, must-revalidate
Content-Type: text/html; charset=utf-8
Date: Thu, 24 May 2012 06:50:45 GMT
Etag: "997dacac05aa4c73f5a6861c9f5a9db0"
Status: 200 OK
Vary: Accept-Encoding
X-Rack-Cache: stale, invalid
X-Request-Id: 078d86423f234da1ac41b418825618c2
X-Runtime: 0.005902
X-Ua-Compatible: IE=Edge,chrome=1
Connection: keep-alive
我做错了什么可怕的事情吗?我觉得那个陈旧、无效的缓存响应有问题……那是我第 4 次点击该页面。
配置信息:
# Use a different cache store in production
config.cache_store = :dalli_store
config.action_dispatch.rack_cache = {
:verbose => true,
:metastore => "memcached://#{ENV['MEMCACHE_SERVERS']}",
:entitystore => "memcached://#{ENV['MEMCACHE_SERVERS']}"#,
}
# OLD : Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
config.static_cache_control = "public, max-age=2592000"
(也许有一种方法可以手动设置缓存控制标头?似乎应该有更简单的方法)。
更新
我什至尝试过将控制器操作降至最低:
def home
expires_in 10.seconds, :public => true
#last_modified = File.mtime("#{Rails.root}/app/views/static_pages/home.html.haml")
#fresh_when last_modified: last_modified , public: true, etag: last_modified
end
而且它不起作用......
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 24 May 2012 19:15:18 GMT
Content-Type: text/html; charset=utf-8
Connection: keep-alive
Status: 200 OK
X-Ua-Compatible: IE=Edge,chrome=1
Etag: "733798214c652f39ae79b4037e9111dc"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: b33087fe0c2ae986c4cac88f14420b7c
X-Runtime: 0.006000
X-Rack-Cache: stale, invalid
Vary: Accept-Encoding
X-Varnish: 349105873
Age: 0
Via: 1.1 varnish
!
【问题讨论】:
-
动作缓存也能做到这一点吗?您是否使用页面缓存对其进行了测试,只是为了查看标题有何不同?
-
嗯,我明白你的意思了。如果 Rack::Cache 正确设置为提供页面(不是最干净的方法,但你可以在 Heroku 上做的最好),我真的不应该有任何缓存操作。我想我只是把它放在那里。我会试着把它拿出来看看会发生什么。会尽快回复您。
-
看来你是对的。当我取出动作缓存时,标头已正确设置。我不知道我一定明白这一点。设置 HTTP 响应标头不应该与缓存操作结果分开吗?即,我是否应该能够缓存我的 rails 应用程序的响应(动作缓存)但仍然设置 HTTP 标头,以便如果用户重新请求页面,他们根本不会访问服务器(提供正确的设置在 max-age 标题上?)
-
是的,我不完全确定。我的印象是,动作缓存的全部意义在于访问应用服务器——您可能有过滤器(用于身份验证或其他)——无论请求标头如何。否则,你怎么能依赖你的 before_filter 被适当地调用?
标签: ruby-on-rails caching heroku rack-cache