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



我正在尝试在Memcache中缓存天气预报员的响应(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'

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

在给定的 gem 代码库yahoo_weatherman是不可能的。

原因是yahoo_weatherman gem 的ResponseNokogiri::XML::NodeSet 的形式封装 XML 响应,该响应无法序列化,因此无法缓存。

为了规避这个问题,我们可以对Weathernan::Client类进行猴子修补,以便我们访问 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

相关内容

  • 没有找到相关文章

最新更新