“你正在尝试缓存一个无法序列化为memcached的Ruby对象。”

时间:2013-10-28 02:38:38

标签: ruby-on-rails ruby ruby-on-rails-3 caching dalli

我在多个网站上分享了一个页脚的缓存问题,我想知道可能会出现什么问题。这是错误消息和回溯:

 Cache read: remote_footer_information ({:expires_in=>300 seconds})
 Cache generate: remote_footer_information ({:expires_in=>300 seconds})
 Cache write: remote_footer_information ({:expires_in=>300 seconds})
 Marshalling error for key 'remote_footer_information': no _dump_data is defined for class Proc
 You are trying to cache a Ruby object which cannot be serialized to memcached.

 /app/vendor/bundle/ruby/1.9.1/gems/dalli-2.6.4/lib/dalli/server.rb:397:in `dump'
    /app/vendor/bundle/ruby/1.9.1/gems/dalli-2.6.4/lib/dalli/server.rb:397:in `serialize'
    /app/vendor/bundle/ruby/1.9.1/gems/dalli-2.6.4/lib/dalli/server.rb:269:in `set'
    /app/vendor/bundle/ruby/1.9.1/gems/dalli-2.6.4/lib/dalli/server.rb:60:in `request'
    /app/vendor/bundle/ruby/1.9.1/gems/dalli-2.6.4/lib/dalli/options.rb:18:in `block in request'
    /app/vendor/ruby-1.9.3/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
    /app/vendor/bundle/ruby/1.9.1/gems/dalli-2.6.4/lib/dalli/options.rb:17:in `request'
    /app/vendor/bundle/ruby/1.9.1/gems/dalli-2.6.4/lib/dalli/client.rb:348:in `perform'
    /app/vendor/bundle/ruby/1.9.1/gems/dalli-2.6.4/lib/dalli/client.rb:199:in `set'
    (eval):7:in `block in set_with_newrelic_trace'
    ...

这里是定义缓存检索的地方:

require 'httparty'

module Myclassname
  class Footer
    include HTTParty
    format :json
    attr_accessor :response

    def initialize
      @response = Rails.cache.fetch("remote_footer_information", :expires_in => 5.minutes) do
        begin
          self.class.get("http://www.myappname.net/pages/my_footer.json")
        rescue
          false
        end
      end
    end

    def valid?
      unless @response == false || @response.blank?
        return @response['footer'] != nil
      end

      false
    end

    def footer
      unless @response == false || @response.blank?
        return @response['footer']
      end

      nil
    end

  end
end

这就是视图中的地方。

<%= yield :footer_legend %>

<div class="clearer"></div>
<div class="divider">
</div>

<% response = Myclassname::Footer.new %>
<% if response && response.valid? %>
    <%= response.footer.html_safe %>
<% end %>

我在这里做错了什么?任何想法将不胜感激。谢谢!

3 个答案:

答案 0 :(得分:8)

显然Httparty::Response返回的Httparty.get对象不可序列化,需要缓存。尝试缓存您需要的响应部分,例如

response = self.class.get("http://www.myappname.net/pages/my_footer.json")
response['footer'] if response

问题描述为here

答案 1 :(得分:1)

将HTTParty响应转换为哈希对我有用。

Rails.cache.fetch(cache_key) do
  HTTParty.get(url).to_hash
end

答案 2 :(得分:0)

从httparty版本0.16.3开始。 HTTParty :: Response对象是可缓存的。

例如您现在可以立即将响应对象缓存在缓存存储中:

response = HTTParty.get(...)

store.set(key, Marshal.dump(response))