在 Sinatra 中缓存 twitter gem 推文的简单方法? [英] Simple way to cache twitter gem tweet in Sinatra?

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

问题描述

我遇到了 API 限制请求,最终导致我的网站崩溃.

I'm running into API Limit Requests which end up blowing my site up.

现在为了避免我在救援块中收到来自 Twitter gem 的推文请求,如果发生不好的事情,它会返回一个默认字符串.

Right now to avoid that I have the tweet request from the Twitter gem in a rescue block that returns a default string if something bad happens.

我想知道使用以下方法缓存最新推文的最佳方法是什么:

I'm wondering what would be the best way to cache the latest tweet simply using:

  @twitter = Twitter.user_timeline("some_user", :include_rts => 1, :count => 1).first

如果达到 API 限制?

In case the API limit is hit?

推荐答案

我使用 memcache(或者现在 dalli) 类似的东西.有两种选择.您可以先访问缓存,如果时间戳在某个阈值内,只需返回缓存值,而不会导致 API 命中.或者,您可以使用 API,缓存该值,如果超过 API 阈值,则在您的救援块中返回缓存的值.

I use memcache (or now dalli) for stuff like that. There are two options. You could hit the cache first and if the timestamp is within a certain threshold, just return the cached value without incurring an API hit. Or you could use the API, cache the value, and in your rescue block return the cached value if you exceed the API threshold.

require "memcache"
cache = MemCache.new...
...
@twitter = cache.get("some_user").first
if @twitter.nil?
  begin
    @twitter = Twitter.user_timeline... 
    cache.set("some_user", @twitter) if @twitter
  rescue ...
    @twitter = default
  end
end

require "memcache"
cache = MemCache.new...
...
begin
  @twitter = Twitter.user_timeline...
  cache.set("some_user", @twitter) if @twitter
rescue...
  @twitter = cache.get("some_user").first||default
end

当然,您需要在服务器上运行 memcached 守护进程.

Then of course you'll need to be running the memcached daemon on the server.

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

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