Created
April 19, 2016 18:08
-
-
Save sharshenov/34f6a1ff5eebe414d7dd8b4ecbfc788c to your computer and use it in GitHub Desktop.
Basic throttler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Throttler | |
class << self | |
def limit *attrs | |
throttler.limit *attrs | |
end | |
private | |
def throttler | |
@throttler ||= new | |
end | |
end | |
attr_reader :storage | |
def initialize storage=nil | |
@mutex = Mutex.new | |
@storage = storage || Hash.new | |
end | |
def limit seconds, key='default' | |
while not allowed?(seconds, key) | |
sleep 0.01 | |
end | |
yield if block_given? | |
end | |
private | |
def allowed? seconds, key | |
@mutex.synchronize do | |
now = Time.now.to_f | |
timestamp = get(key) | |
if timestamp.nil? or timestamp < now - seconds | |
set(key, now) | |
true | |
else | |
false | |
end | |
end | |
end | |
def get key | |
value = storage[key] | |
if value and not value.is_a?(Float) | |
value.to_f | |
else | |
value | |
end | |
end | |
def set key, value | |
storage[key] = value | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage examples
Limit rate
Limit rate with personal lock
Use Redis as key-value storage