我正在使用我用Sinatra制作的API构建一个简单的应用程序,该API返回一些JSON。这是相当多的JSON,我的应用程序的API依赖于对其他API的数百个请求。
我可能会缓存5天左右的结果,数据完全没有问题。我只是不能100%确定如何实现缓存。我该如何使用Sinatra来做这件事?
发布于 2011-12-13 13:23:45
就我个人而言,比起memcached,我更喜欢使用redis来处理这类事情。我有一个应用程序,我在相当广泛地使用redis,使用它的方式类似于你所描述的。如果我进行一个没有缓存的调用,页面加载时间超过5秒,使用redis,加载时间下降到0.3秒左右。您还可以设置过期时间,该时间可以很容易地更改。我会这样做,以便从缓存中检索数据。
require 'redis'
get '/my_data/:id' do
redis = Redis.new
if redis[params[:id]]
send_file redis[params[:id]], :type => 'application/json'
end
end
然后,当您想要将数据保存到缓存时,可能如下所示:
require 'redis'
redis = Redis.new
<make API calls here and build your JSON>
redis[id] = json
redis.expire(id, 3600*24*5)
发布于 2011-12-13 12:38:28
get '/my_data/:id' do
# security check for file-based caching
raise "invalid id" if params[:id] =~ /[^a-z0-9]/i
cache_file = File.join("cache",params[:id])
if !File.exist?(cache_file) || (File.mtime(cache_file) < (Time.now - 3600*24*5))
data = do_my_few_hundred_internal_requests(params[:id])
File.open(cache_file,"w"){ |f| f << data }
end
send_file cache_file, :type => 'application/json'
end
别忘了mkdir cache
。
或者,您也可以使用memcache-client
,但它将要求您在系统范围内安装memcached
。
https://stackoverflow.com/questions/8486596
复制