Ruby on Rails实战之一:巧妙解决页面片段缓存陷阱

Rails的片段缓存fragment cache有一个很隐蔽的陷阱。在Rubyconf China 2009会上,牛人Robin Lu向大家详细讲解了这个陷阱(他演讲的ppt在http://www.scribd.com/doc/15705678/Ruby-on-Rails-Pitfall?autodown=pdf 可以看到),最后也提出了3种解决方案,不过我觉得这3种方案都不太令人满意,下面分享一下我的解决方案。

 

首先,有必要简单介绍一下Rails的这个片段缓存陷阱。大家先看一下代码:

 

#code in the controller

class BlogController < ApplicationController
   def list
       unless read_fragment("/blog/list/articles")
           @articles = Article.find(:all)
       end
   end 
end

#code in the view
<% cache("/blog/list/articles") do %>
  <ul>
  <% for article in @articles do %>
     <li> <p> <%=h(article.body)%> </p></li>
   <% end %>
  </ul>
<% end %>

这是很多人使用片段缓存的做法,大概是受了那本经典教程影响的缘故。在并发量不大的情况下,这段代码不会产生问题,但是在并发量一大很容易会crash,提示信息是@articles未赋值。其原因在于,在action中检查缓存和view中使用缓存中间存在时间间隔。设想一下:一个过程在action中found cache,于是未获取@articles,但是执行到view时,缓存被另外的进程清空了,这个时候使用@articles就会报异常。

 

Robin提到的三种方法是:

1.处理异常,提示用户刷新页面。这种方法对用户体验而言,不友好。

2.在view处理的地方获取@articles。这种方法让view中充斥代码,不优雅。

3.更新缓存内容而不是清空缓存。这种方法需要额外处理,不爽。

 

我的解决方法其实非常简单改写cache方法和fragment_exists?方法,在action中使用fragment_exists?检查缓存,如果找到,就把读到的内容置到实例变量中,在view的cache方法中,使用该实例变量。 多说无益,看一下代码

就明白了。

插件smart_fragment_cache 中的核心代码

module ActionController #:nodoc:
  module Caching
    module Fragments       
      #override fragment_exist?
      def fragment_exists?(name, options=nil)
        @internal_smart_caches ||= {}
        key = fragment_cache_key(name)
        @internal_smart_caches[key] = read_fragment(name, options)    
      end      
      
      #cache_miss?
      def fragment_miss?(name, options=nil)
         !fragment_exists?(name,options)       
      end
      
      #override fragment_for
      def fragment_for(buffer, name = {}, options = nil, &block) #:nodoc:
        if perform_caching
          if cache = smart_read_fragment(name, options)
            buffer.concat(cache)
          else
            pos = buffer.length
            block.call
            write_fragment(name, buffer[pos..-1], options)
          end
        else
          block.call
        end
      end      
      
      #smart_read_fragment
      def smart_read_fragment(name, options=nil)
          key = fragment_cache_key(name)
          (@internal_smart_caches and @internal_smart_caches[key]
) or read_fragment(name, options)     
      end
    end
  end
end
 

使用插件后,刚才的代码改写成

#code in the controller

class BlogController < ApplicationController
   def list
       unless fragment_exists?("/blog/list/articles")
           @articles = Article.find(:all)
       end
   end 
end

#code in the view
<% cache("/blog/list/articles") do %>
  <ul>
  <% for article in @articles do %>
     <li> <p> <%=h(article.body)%> </p></li>
   <% end %>
  </ul>
<% end %>
 

代码只有一处细小变化,action中 read_fragment 变为 fragment_exists?。使用这个方案,有三个好处:

1.检查和使用缓存数据只发生一次,高并发下不会触发异常,更安全;

2.只执行一次获取缓存动作,更高效;

3.不需要额外处理,同时保持了view中代码清洁,更优雅。

 

插件 smart_fragment_cache刚刚写成,目前只针对 Rails 2.3.2版本,先提供附件下载吧,等我弄好后再正式发布出来,希望对大家有帮助。

 

 

 

 

 

 

 

 

根据原作 https://pan.quark.cn/s/0ed355622f0f 的源码改编 野火IM解决方案 野火IM是专业级即时通讯和实时音视频整体解决方案,由北京野火无限网络科技有限公司维护和支持。 主要特性有:私有部署安全可靠,性能强大,功能齐全,全平台支持,开源率高,部署运维简单,二次开发友好,方便与第三方系统对接或者嵌入现有系统中。 详细情况请参考在线文档。 主要包括一下项目: 野火IM Vue Electron Demo,演示如何将野火IM的能力集成到Vue Electron项目。 前置说明 本项目所使用的是需要付费的,价格请参考费用详情 支持试用,具体请看试用说明 本项目默认只能连接到官方服务,购买或申请试用之后,替换,即可连到自行部署的服务 分支说明 :基于开发,是未来的开发重心 :基于开发,进入维护模式,不再开发新功能,鉴于已经终止支持且不再维护,建议客户升级到版本 环境依赖 mac系统 最新版本的Xcode nodejs v18.19.0 npm v10.2.3 python 2.7.x git npm install -g node-gyp@8.3.0 windows系统 nodejs v18.19.0 python 2.7.x git npm 6.14.15 npm install --global --vs2019 --production windows-build-tools 本步安装windows开发环境的安装内容较多,如果网络情况不好可能需要等较长时间,选择早上网络较好时安装是个好的选择 或参考手动安装 windows-build-tools进行安装 npm install -g node-gyp@8.3.0 linux系统 nodej...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值