39 lines
1023 B
Ruby
39 lines
1023 B
Ruby
|
||
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 |