加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

ruby-on-rails – 在Rails中将memcached作为Object存储

发布时间:2020-12-16 05:52:57 所属栏目:安全 来源:网络整理
导读:我在我的Rails应用程序中使用Memcached作为Object Store,我在其中存储了memcached中User对象的搜索结果 现在,当我获取数据时,我得到了Memcached Undefined Class / Module Error.我在这个博客中找到了解决这个问题的方法 http://www.philsergi.com/2007/06/r
我在我的Rails应用程序中使用Memcached作为Object Store,我在其中存储了memcached中User对象的搜索结果

现在,当我获取数据时,我得到了Memcached Undefined Class / Module Error.我在这个博客中找到了解决这个问题的方法

http://www.philsergi.com/2007/06/rails-memcached-undefinded-classmodule.html

before_filter :preload_models
  def preload_models
    Model1
    Model2
  end

建议事先预装模型.我想知道是否有一个更优雅的解决方案来解决这个问题,并且使用预加载技术有任何缺点.

提前致谢

解决方法

我也有这个问题,我想我想出了一个很好的解决方案.

您可以覆盖fetch方法并挽救错误并加载正确的常量.

module ActiveSupport
  module Cache
    class MemCacheStore
      # Fetching the entry from memcached
      # For some reason sometimes the classes are undefined
      #   First rescue: trying to constantize the class and try again.
      #   Second rescue,reload all the models
      #   Else raise the exception
      def fetch(key,options = {})
        retries = 2 
        begin
          super
        rescue ArgumentError,NameError => exc         
          if retries == 2
            if exc.message.match /undefined class/module (.+)$/
              $1.constantize
            end
            retries -= 1
            retry          
          elsif retries == 1
            retries -= 1
            preload_models
            retry
          else 
            raise exc
          end
        end
      end

      private

      # There are errors sometimes like: undefined class module ClassName.
      # With this method we re-load every model
      def preload_models     
        #we need to reference the classes here so if coming from cache Marshal.load will find them     
        ActiveRecord::Base.connection.tables.each do |model|       
          begin       
            "#{model.classify}".constantize 
          rescue Exception       
          end     
        end       
      end
    end
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读