forgeplus/app/services/sliding_window_rate_limiter.rb

39 lines
1023 B
Ruby
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

class SlidingWindowRateLimiter
def initialize(user_id, rate, window_size)
@rate = rate # 请求速率限制(每秒的请求数)
@window_size = window_size # 时间窗口大小(秒)
@redis = $redis_cache
@key = "#{user_id}:SlidingWindow"
@current_timestamp = Time.now.to_f
end
def allow_request
current_timestamp = Time.now.to_f
score = current_timestamp.to_i
start_time = current_timestamp - @window_size
@redis.zremrangebyscore(@key, '-inf', start_time)
count = @redis.zcount(@key, '-inf', '+inf').to_i
return false if count >= @rate
@redis.zadd(@key, score, current_timestamp)
true
end
end
=begin
#测试通过
limiter = SlidingWindowRateLimiter.new(user_id,10, 1) # 设置请求速率限制为10次/秒时间窗口大小为1秒
40.times do
if limiter.allow_request
puts "Allow"
else
puts "Reject"
end
end
=end