Created
January 24, 2020 15:10
-
-
Save mrk21/275ad20f1cc9927dc9e389037d6e794a to your computer and use it in GitHub Desktop.
Locking between multiple Ruby processes by Redis
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 Lock | |
def initialize(redis:, key:) | |
@redis = redis | |
@key = key | |
end | |
def lock(timeout_sec: 10) | |
start = Time.now.to_i | |
loop do | |
break yield if @redis.setnx(@key, true) | |
raise Timeout::Error if (Time.now.to_i - start) >= timeout_sec | |
sleep 0.001 # 1ms | |
end | |
ensure | |
@redis.del(@key) | |
end | |
end | |
hoge_lock = Lock.new(redis: Redis.new, key: 'hoge') | |
hoge_lock.lock { puts 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment