1

我编写了一个小的 Sinatra 脚本来获取用户的 2 条推文,并按其编号的降序显示 10 个转发者。追随者:

拼图/puzzle.rb

require 'twitter'
require 'json'
require 'sinatra'
#require 'haml'

client = Twitter::REST::Client.new do |config|
    config.consumer_key        = ""
    config.consumer_secret     = ""
    config.access_token        = ""
    config.access_token_secret = ""
end

set :server, 'webrick'

set :haml, :format => :html5

get '/' do
  content_type :json
  arr = []
        retweeters = client.retweeters_of(429627812459593728)

        retweeters.each do |retweeter|
            ob = {}
            ob[:name] = retweeter.name
            ob[:followers_count] = retweeter.followers_count
            arr.push(ob)
        end


    # remove the duplicates and sort on the users with the most followers,
    sorted_influencers = arr.sort_by { |hsh| hsh[:followers_count] }
    sorted_influencers.reverse!
    sorted_influencers[0..9].to_s
end

我正在尝试处理速率限制。

如何缓存 json 输出以避免超出速率限制?

4

1 回答 1

1

假设您保持非常简单的场景,您可以使用一个小的自定义类来存储信息并提供线程安全的方法(从您的问题中不清楚您的问题到底在哪里,但无论如何都会出现这个问题):

require 'json'
require 'sinatra'
require 'date'
require 'thread'
require 'twitter'

set :server, 'webrick'

set :haml, :format => :html5

class MyCache
  def initialize()
    @mutex = Mutex.new
    @last_update = DateTime.new            # by default, -4732 BC
    @client = Twitter::REST::Client.new do |config|
      config.consumer_key        = ""
      config.consumer_secret     = ""
      config.access_token        = ""
      config.access_token_secret = ""
    end
  end

  def get_cache
    @mutex.synchronize do
      if DateTime.now - @last_update > 10.0 / (3600 * 24)
        @last_update = DateTime.now

        arr = []
        retweeters = @client.retweeters_of(429627812459593728)

        retweeters.each do |retweeter|
          ob = {}
          ob[:name] = retweeter.name
          ob[:followers_count] = retweeter.followers_count
          arr.push(ob)
        end

        # remove the duplicates and sort on the users with the most followers,
        sorted_influencers = arr.sort_by { |hsh| hsh[:followers_count] }
        sorted_influencers.reverse!
        @cache = sorted_influencers[0..9].to_s
      end

      @cache
    end
  end
end

my_cache = MyCache.new

get '/' do
  content_type :json
  my_cache.get_cache
end

这个版本现在包括所有需要的东西。我使用 @client 来存储 twitter 客户端的实例(我想它是可重用的),还要注意整个代码是如何在if语句中的,最后我们更新@cache. 如果你不熟悉 Ruby,块的值是由它的最后一个表达式决定的,所以当我一个人写的时候@cache,就好像我写了return @cache.

于 2014-02-03T05:42:05.703 回答