在Rails应用程序中缓存对外部API的调用

编程入门 行业动态 更新时间:2024-10-09 21:26:15
本文介绍了在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的调用

本文发布于:2023-11-28 06:05:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641227.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   应用程序   Rails   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!