Rails中Cache的那些事
在Rails中做缓存是简单的,要开启cache的话
config.action_controller.perform_caching = true
默认情况下只有production是true,其他ENV都是false。
Rails中存储cache的方式多了去了,现在用的最多的应该是memcache吧。rails的guildes中有句Page caches are always stored on disk,貌似是所有的page cache都用filestore?在environment.rb中指定使用的store模式
ActionController::Base.cache_store = :file_store, "/path/to/cache/dir"
只要上面两句话都配置好了,下面就简单的在需要cache的地方加几条语句就成
1、Fragment cache
就是缓存一个片段,将需要缓存的内容放入一个block中即可
<% cache do %> something to cache <% end %>
如果要expire一个片段可以用expire_fragment方法,
expire_fragment(:controller => 'articles', :action => 'list')
2、Page cache和Action cache
class Article < AR::Base before_filter :authenticate, :only => [:edit, :create] caches_page :index caches_action :edit def index;end def edit;end def create expire_page :action => 'index' expire_action :action => 'edit' end end
貌似caches_action和caches_page的区别也就只是action需要request经过一次rails stack,那也就能给要cache的action加点filter了;而page的话就完全不会经过rails了,直接就访问静态缓存的文件去了。。。
3、使用Sweeper管理cache
Swepper就是一个Observer,会在监视到一个特定的Model发生某些特定的callback时执行特定的活动,比如expire缓存
class ArticleSweeper < AC::Caching::Sweeper observe Article def after_create expire_page :controller => 'articles', :action => 'index' expire_action :controller =>' articles', :action => 'edit' expire_fragment :controller => 'articles', :action => 'list' end end
4、浏览器端的缓存
通过stale?方法来判断Headers中的etag和last_modifiled是否与server上的一致
def show @article = Article.find(params[:id]) if stale?(:etag => @article, :last_modifiled=>@article.updated_at.utc) respond_to do |format| end end end
然后就是memcache相关的了,有时间再记录
完工,就这些要写的,不是guides,个人看的小小笔记,下面是关于这方面的很好的文档:
http://guides.rubyonrails.org/caching_with_rails.html
http://neeraj.name/blog/articles/862-memcached-and-cache_fu
http://code.google.com/p/memcached/wiki/FAQ
http://www.themomorohoax.com/2009/01/07/using-stale-with-rails-to-return-304-not-modified
PS:Rails是不是很Agile?哈哈,Rails学起来Agile,用起来也Agile。。。
本文基于 署名-非商业性使用-禁止演绎 2.5 中国大陆 发布
6 COMMENTS >>LEAVE<<
-
很强大,php做缓存都得自己操心做类
尽用些我不会英文单词...
-
看代码的确很agile的说。。。
-
@wayne
不看代码也很agile。。。
-
@kangzj
哈哈,这应该不算英文单词,只是Rails中常用的一些术语。。。
-
那这个呢? Agile
-
@kangzj
时下最流行的敏捷开发啊Agile Development