在 Rails 应用中缓存对外部 API 的调用 [英] Caching calls to an external API in a rails app
问题描述
rails 应用程序 (4) 使用 HTTParty 调用外部 API.API 是只读的.需要缓存,因为数据不会经常更改(24 小时),并且 API 每小时只允许有限数量的调用.
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.
我想我需要某种基于哈希的缓存,我将使用params/sent/to/the/api"作为键.用于缓存的 Rails 工具似乎只适用于页面、片段或 SQL.
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.
我应该怎么做才能缓存对外部 API 的调用?
What should I do to cache calls to an external API?
推荐答案
它会是这样的.基本上,Rails.cache.fetch 调用将包装您的 API 调用.除非缓存过期,否则它不会命中 API.
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
请确保您的环境中设置了缓存.Memcache 非常适合这类事情.
Be sure you have a cache set in your environment. Memcache works great for this sort of thing.
这篇关于在 Rails 应用中缓存对外部 API 的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!