There are only two hard problems in Computer Science: cache invalidation and naming things. - Phil Karlton
Fortunately, Rails has made it perfect!
config.action_controller.perform_caching = true
Rails.cache
读
Rails.cache.write 'foo', 'bar'
写
Rails.cache.read 'foo'
不存在则写,存在则读
Rails.cache.fetch 'a_big_data' do { (1..1000000).inject(:+) }
文件位置
./tmp/cache
def body_html
Rails.cache.fetch "#{cache_key}/body_html" do
render(body)
end
end
Rails.cache
<%= cache @post do %>
<p>
<b>Title:</b>
<%= @post.title %>
</p>
<p>
<b>Content:</b>
<%= @post.content %>
</p>
<% end %>
手动设置过期
expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products')
cache 'explicit-key' # views/explicit-key
cache @post # views/posts/2-1283479827349
cache [@post, 'sidebar'] # views/posts/2-2348719328478/sidebar
cache [@post, @comment] # views/posts/2-2384193284878/comments/1-2384971487
cache :hash => :of_things # views/localhost:3000/posts/2?hash_of_things
caches_action :index, :cache_path => proc {|c| { :tag => Post.maximum('updated_at') } }
caches_page :index
特点:
public
目录生成静态html结尾文件,此后访问就会跳过所有validation和filter。Cache-Control: max-age=0, private, must-revalidate
def show
@post = Post.find params[:id]
if stale? @post, :etag => @post.posted_at do
respond_with @post
end
end
belongs to
和 :touch => true
结合使用Rails.cache
来缓存查询到的数据http://www.broadcastingadam.com/2012/07/advanced_caching_revised/