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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在Rails中将memcached作为Object存储前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在我的Rails应用程序中使用Memcached作为Object Store,我在其中存储了memcached中User对象的搜索结果

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

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

  1. before_filter :preload_models
  2. def preload_models
  3. Model1
  4. Model2
  5. end

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

提前致谢

解决方法

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

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

  1. module ActiveSupport
  2. module Cache
  3. class MemCacheStore
  4. # Fetching the entry from memcached
  5. # For some reason sometimes the classes are undefined
  6. # First rescue: trying to constantize the class and try again.
  7. # Second rescue,reload all the models
  8. # Else raise the exception
  9. def fetch(key,options = {})
  10. retries = 2
  11. begin
  12. super
  13. rescue ArgumentError,NameError => exc
  14. if retries == 2
  15. if exc.message.match /undefined class\/module (.+)$/
  16. $1.constantize
  17. end
  18. retries -= 1
  19. retry
  20. elsif retries == 1
  21. retries -= 1
  22. preload_models
  23. retry
  24. else
  25. raise exc
  26. end
  27. end
  28. end
  29.  
  30. private
  31.  
  32. # There are errors sometimes like: undefined class module ClassName.
  33. # With this method we re-load every model
  34. def preload_models
  35. #we need to reference the classes here so if coming from cache Marshal.load will find them
  36. ActiveRecord::Base.connection.tables.each do |model|
  37. begin
  38. "#{model.classify}".constantize
  39. rescue Exception
  40. end
  41. end
  42. end
  43. end
  44. end
  45. end

猜你在找的Memcache相关文章