Ruby on rails memcached作为Rails中的对象存储
我在Rails应用程序中使用Memcached作为对象存储,其中存储的搜索结果是Memcached中的用户对象 现在,当我取出数据时,我得到了Memcached未定义的类/模块错误。我在这个博客中找到了解决这个问题的方法 建议在手动之前预加载模型。我想知道是否有一个更优雅的解决方案来解决这个问题,以及使用预加载技术是否有任何缺点Ruby on rails memcached作为Rails中的对象存储,ruby-on-rails,memcached,models,eager-loading,Ruby On Rails,Memcached,Models,Eager Loading,我在Rails应用程序中使用Memcached作为对象存储,其中存储的搜索结果是Memcached中的用户对象 现在,当我取出数据时,我得到了Memcached未定义的类/模块错误。我在这个博客中找到了解决这个问题的方法 建议在手动之前预加载模型。我想知道是否有一个更优雅的解决方案来解决这个问题,以及使用预加载技术是否有任何缺点 提前感谢我也遇到了这个问题,我想我找到了一个很好的解决方案 您可以覆盖fetch方法,挽救错误并加载正确的常量 module ActiveSupport modu
提前感谢我也遇到了这个问题,我想我找到了一个很好的解决方案 您可以覆盖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
今天遇到了这个问题,设法想出了一个更简洁的解决方案,应该适用于所有类
Rails.cache.instance_eval do
def fetch(key, options = {}, rescue_and_require=true)
super(key, options)
rescue ArgumentError => ex
if rescue_and_require && /^undefined class\/module (.+?)$/ =~ ex.message
self.class.const_missing($1)
fetch(key, options, false)
else
raise ex
end
end
end
不确定为什么[MemCacheStore]
没有调用的是[MemCacheStore.const_missing]
方法,所有调用都以正常的“Rails-y”方式进行。但是,这应该效仿它
干杯
Chris此解决方案非常好,但仅限于活动唱片型号。有时您会缓存非AR类,在这种情况下,我认为您必须求助于此线程上的第一个解决方案。@KonstantinGredeskoul只需跳过预加载部分即可
Rails.cache.instance_eval do
def fetch(key, options = {}, rescue_and_require=true)
super(key, options)
rescue ArgumentError => ex
if rescue_and_require && /^undefined class\/module (.+?)$/ =~ ex.message
self.class.const_missing($1)
fetch(key, options, false)
else
raise ex
end
end
end