Caching calls to an external API in a rails app

2019-02-14 13:46发布

The rails app (4) calls an external API using HTTParty. The API is read only. Caching is required as the data does not change often (24h) and the API allow only a limited number of calls per hour.

I guess I need some kind of hash based cache where I will use "params/sent/to/the/api" as key. Rails tools for caching seems only to be for pages,fragments or SQL.

What should I do to cache calls to an external API?

1条回答
该账号已被封号
2楼-- · 2019-02-14 13:48

It'll be something like this. Basically, the Rails.cache.fetch call will wrap your API call. It won't hit the API unless the cache has expired.

class Results

  def get(url, params)
    Rails.cache.fetch([url, params], :expires => 1.hour) do
      HTTParty.get('url/to/api')
    end
  end

end

Be sure you have a cache set in your environment. Memcache works great for this sort of thing.

查看更多
登录 后发表回答