Rails 中的缓存

需要缓存的

  • 全静态页面
  • 数据库密集访问 但又几乎无变化的动态页面
  • 动态页面的片段

 

 

开发环境开启缓存

/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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值