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的调用
发布评论