需要缓存的
- 全静态页面
- 数据库密集访问 但又几乎无变化的动态页面
- 动态页面的片段
开发环境开启缓存
/config/environments/development.rb
config.action_controller.perform_caching = true
如果动态页面不经常更改,可以使用页面级的缓存。Page Cache AND Fragment Cache
页面和分段缓存二者均在控制器级别发生。
清单 1. 页面缓存 Page Cache
class FooController < ApplicationController
caches_page :privacy_policy, :user_agreement
end
清单 2. 分段缓存 Fragment Cache 【不涉及request 的动态params】
<% cache 'gifts_index' do %>
<h3>
Here, you can make the world a better place with a single gift. Donation gifts
are also a wonderful way to honor friends and family. Just imagine what we
can achieve together.
</h3>
<h2 class="lightBlue"><%= @event_title %></h2>
<div id="homefeatureitems">
<% for gift in @event_gifts %>
<%= render :partial => 'gifts/listable', :locals => { :gift => gift } %>
<% end %>
</div>
...
<% end %>
清单 3. 分段缓存 Fragment Cache 【URL标识】
<% cache @cause.permalink(params[:id]) do %>
页面缓存优势是速度快。缺点是伪静态,不走后台。
实际上,很多action都有before filter。如果要先身份认证才能访问页面,页面缓存不行。
动作缓存让你能够利用控制器上的任何过滤器。
清单 4. 动作缓存
class FoooController < ApplicationController
caches_action :secret_page, :secret_list
end
最后 cache expire
- 缓存到期失效
- 数据更新
清单 5. 基于时间的缓存到期
# -*- encoding : utf-8 -*-
class HomeController < ApplicationController
layout "home_manage"
skip_before_filter :verify_authenticity_token, :only => [:upload_img]
caches_action :index, :expires_in => 1.days
# before_filter :get_vote
end
清单 6. 使缓存失效
# -*- encoding : utf-8 -*-
class HomeSweeper < ActionController::Caching::Sweeper
observe HomeRecommend, HomeKv, HomeBanner, FitLiteral, FitImage, Question, OwnerEnter,
HomeImageLibPhoto, HomeDesignShow, HomeLifeVideo, IBanner
def after_create(model)
# expire_action("/index")
expire_index
end
def after_update(model)
# expire_action("/index")
expire_index
end
def after_destroy(model)
# expire_action("/index")
expire_index
end
def expire_index
cache_key = "views/#{request.host_with_port}/index"
Rails.cache.delete(cache_key)
end
end
参考链接:
https://www.ibm.com/developerworks/cn/web/wa-rails1/