2010-12-08 44 views
1

我正在运行API限制请求,最终将我的站点吹起来。在Sinatra中缓存twitter gem tweet的简单方法?

现在,为了避免这种情况,我在救援块中发布了来自Twitter gem的推特请求,如果发生不良情况,它会返回默认字符串。

我想知道什么是缓存最新的鸣叫最好的办法简单地使用:

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

万一API限制被击中?

回答

2

我使用memcache(或现在dalli)这样的东西。有两种选择。您可以首先点击缓存,如果时间戳在一定的阈值内,只需返回缓存的值而不会导致API命中。或者您可以使用该API,缓存该值,并且如果超出API阈值,则在您的救援块中返回缓存的值。

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守护进程。