在Sinatra中缓存响应的最佳方法? [英] Best way to cache a response in Sinatra?

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

问题描述

我正在使用通过Sinatra制作的API来构建一个简单的应用程序,该API返回一些JSON。它有很多JSON,我的应用程序的API依赖于对其他API的数百个请求。



我大概可以将结果缓存5天左右,数据。我只是不确定100%如何实现缓存。我该如何使用Sinatra做到这一点?我有一个可以广泛使用redis的应用程序,其使用方式与您所描述的类似。如果我拨打的电话未缓存,则页面加载时间会超过5秒(使用redis),加载时间会降至0.3秒左右。您还可以设置过期时间,可以很容易地更改它。我会像这样从缓存中检索数据。

  require'redis'
get'/ my_data /:id'do
redis = Redis.new
如果redis [params [:id]]
send_file redis [params [:id]],:type => 'application / json'
结束
结束

然后在您想要保存时将数据存储到缓存中,也许是这样的:

  require'redis'
redis = Redis.new
<在此处进行API调用并构建JSON>
redis [id] = json
redis.expire(id,3600 * 24 * 5)


I'm building a simple app on the side using an API I made with Sinatra that returns some JSON. It's quite a bit of JSON, my app's API relies on a few hundred requests to other APIs.

I can probably cache the results for 5 days or so, no problem with the data at all. I'm just not 100% sure how to implement the caching. How would I go about doing that with Sinatra?

解决方案

Personally, I prefer to use redis for this type of things over memcached. I have an app that I use redis in pretty extensively, using it in a similar way to what you described. If I make a call that is not cached, page load time is upwards of 5 seconds, with redis, the load time drops to around 0.3 seconds. You can set an expires time as well, which can be changed quite easily. I would do something like this to retrieve the data from the cache.

require 'redis'
get '/my_data/:id' do
  redis = Redis.new
  if redis[params[:id]]
    send_file redis[params[:id]], :type => 'application/json'
  end
end

Then when you wanted to save the data to the cache, perhaps something like this:

require 'redis'
redis = Redis.new
<make API calls here and build your JSON>
redis[id] = json
redis.expire(id, 3600*24*5)

这篇关于在Sinatra中缓存响应的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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