每个用户对rails中的函数调用进行速率限制

时间:2011-07-22 01:11:23

标签: ruby-on-rails ruby-on-rails-3 rate-limiting

任何人都知道我怎么会这样做?很难在线查找信息。我发现的最好的是它的宝石,但我只能想到如何实现该应用程序。

2 个答案:

答案 0 :(得分:8)

它可以通过以下方式处理:1)webserver 2)rack-application。一切都取决于你需要什么。我们use内置nginx功能来限制API请求:

     limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;
     limit_req zone=one burst=2;

另一个解决方案是rack-throttle

这是Rack中间件,提供用于限制对Rack应用程序的传入HTTP请求的速率逻辑。您可以将Rack :: Throttle与任何基于Rack的Ruby Web框架一起使用,包括Ruby on Rails 3.0和Sinatra。

答案 1 :(得分:2)

以下是如何使用Redis和时间戳实现它的示例。您可以在user.rb中包含此模块,然后可以调用user.allowed_to?(:reveal_email)

# Lets you limit the number of actions a user can take per time period
# Keeps an integer timestamp with some buffer in the past and each action increments the timestamp
# If the counter exceeds Time.now the action is disallowed and the user must wait for some time to pass.

module UserRateLimiting

  class RateLimit < Struct.new(:max, :per)
    def minimum
      Time.now.to_i - (step_size * max)
    end

    def step_size
      seconds = case per
      when :month  then 18144000 # 60 * 60 * 24 * 7 * 30
      when :week   then 604800   # 60 * 60 * 24 * 7
      when :day    then 86400    # 60 * 60 * 24
      when :hour   then 3600     # 60 * 60
      when :minute then 60
      else raise 'invalid per param (day, hour, etc)'
      end
      seconds / max
    end
  end

  LIMITS = {
    :reveal_email => RateLimit.new(200, :day)
    # add new rate limits here...
  }

  def allowed_to? action
    inc_counter(action) < Time.now.to_i
  end

  private

  def inc_counter action
    rl = LIMITS[action]
    raise "couldn't find that action" if rl.nil?
    val = REDIS_COUNTERS.incrby redis_key(action), rl.step_size
    if val < rl.minimum
      val = REDIS_COUNTERS.set redis_key(action), rl.minimum
    end
    val.to_i
  end

  def redis_key action
    "rate_limit_#{action}_for_user_#{self.id}"
  end

end