在Rails应用程序中缓存对外部API的调用 [英] Caching calls to an external API in a rails app

查看:53
本文介绍了在Rails应用程序中缓存对外部API的调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆