This document discusses caching techniques in Rails, including page caching, action caching, and fragment caching. Page caching stores entire static HTML pages to serve cached content quickly without running Rails. Action caching runs controllers but caches output. Fragment caching caches portions of views. Caches can be expired based on model changes or timed expiration. Plugins like cache_fu and sweeper generators help manage caching.
5. Page Cache
• Rails 内速度最快的一种缓存
• 简单,容易使用
• Cached Page,不必再执行Rails,直接由Web Server
加载静态的Html页面
Shanghai On Rails 2007
6. Page Cache Example
class UsersController < ApplicationController
caches_page :show
def show
…
end
…
end
Shanghai On Rails 2007
7. http://localhost/users/show/100
Rendering users/show
Cached page: /users/show/100.html
$ ls public/users/show
100.html
Shanghai On Rails 2007
8. Page Cache Sweeper
class UserSweeper < ActionController::Caching::Sweeper
observe User
def after_update(record)
expire_page :controller=>:users,:action=>:show,:id=>record.id
end
…
end
class UsersController < ApplicationController
cache_sweeper :user_sweeper
caches_page :show
Shanghai On Rails 2007
13. Action Cache Example
类似于Page Cache:caches_action,expire_action
class UsersController < ApplicationController
before_filter :authenticate
caches_page :show
cache_sweeper :user_sweeper
def show
…
end
end
Shanghai On Rails 2007
14. http://localhost/users/show/100
Rendering users/show
Cached fragment: localhost/users/show/100 (0.00000)
$ ls -al tmp/cache/localhost/users/show/*
… tmp/cache/localhost/users/show/100.cache
Fragment read: localhost/users/show/100 (0.00000)
Shanghai On Rails 2007
16. Action Cache Problem
• 查询字符
caches_action_with_params
expire_action_with_params
Shanghai On Rails 2007
17. Fragment Cache
• 用于cache 视图中代码块
• 默认会在/tmp/cache目录下生成.cache文件
• 清除缓存 expire_fragment
Shanghai On Rails 2007
18. Fragment Cache Example
<%cache do%>
<ul>
<%@users.each do |user|%>
<li><%=link_to user.login,user_path(user)%></li>
<%end%>
</ul>
<%end%>
Shanghai On Rails 2007
25. timed_fragment_cache
• View
<% cache 'fragment_name', 10.minutes.from_now do %>
#the cached fragment which does something intensive
<% end %>
• Controller
when_fragment_expired 'fragment_name', 10.minutes_from_now do
#some intensive code
end
Shanghai On Rails 2007