如何在内存缓存中缓存天气(Nokogiri::XML::NodeSet 对象)?

How to cache Weather (Nokogiri::XML::NodeSet object) in Memcache?

我正在尝试在 Memcache 中缓存 Weatherman 的响应 (https://github.com/dlt/yahoo_weatherman) 以避免多次获取天气,我正在这样做:

  weather = Rails.cache.fetch([:weather_by_woeid, weather.woeid], expires_in: 1.hour) do
    client = Weatherman::Client.new
    client.lookup_by_woeid weather.woeid
  end

但是我遇到了这个异常:

ERROR -- : Marshalling error for key 'Timeline:weather_by_woeid/26352062': no _dump_data is defined for class Nokogiri::XML::NodeSet
ERROR -- : You are trying to cache a Ruby object which cannot be serialized to memcached.
ERROR -- : /var/lib/gems/2.2.0/gems/dalli-2.7.4/lib/dalli/server.rb:402:in `dump'

处理此问题的最佳方法是什么?

yahoo_weathermangem 的给定代码库无法做到这一点。

原因是 Responseyahoo_weatherman gem 以 XML 的形式封装了响应=14=],无法序列化,因此无法缓存。

为了避免这个问题,我们可以对 Weathernan::Client class 进行猴子修补,这样我们就可以访问 Weatherman API 的原始响应,这是一个字符串,可以被缓存.

# Extends the default implementation by a method that can give us raw response
class Weatherman::Client
    def lookup_raw_by_woeid(woeid)
        raw = get request_url(woeid)
    end
end

# We call the lookup_raw_by_woeid and cache its response (string)
weather = Rails.cache.fetch([:weather_by_woeid, weather.woeid], expires_in: 1.hour) do
    client = Weatherman::Client.new
    client.lookup_raw_by_woeid weather.woeid
end

# We now convert that string into a Weatherman response.
w = Weatherman::Response.new(weather)

# Print some values from weather response
p w.wind