ruby-on-rails - Memcached 作为 Rails 中的对象存储

标签 ruby-on-rails memcached models eager-loading

我将 Memcached 用作我的 Rails 应用程序的对象存储,在其中存储搜索结果,这些结果是 memcached 中的用户对象

现在,当我取出数据时,我得到了 Memcached 未定义的类/模块错误。我在这个博客中找到了这个问题的解决方案

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

关于ruby-on-rails - Memcached 作为 Rails 中的对象存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531588/

相关文章:

ruby-on-rails - 模型名称包含 'cache'

ruby-on-rails - 如何用 cucumber 测试sidekiq

ruby-on-rails - 如何正确转义 Active Record where 子句中的正则表达式

ruby-on-rails - 如何从 params 哈希中删除空参数?

caching - Varnish 和 ESI : Fetching in parallel and possible workarounds

json - 将 JSON 解码为 Go 接口(interface){}

ruby-on-rails - 删除记录时的 SystemStackError(堆栈级别太深)

java - 共享Memcache能保证列表的顺序吗?

javascript - 如何使用 node.js 创建用户模型?

mysql - ruby on rails 的循环模型依赖