2014-04-11 13:43:33 +08:00
|
|
|
# Cross-process locking using Redis.
|
|
|
|
class DistributedMutex
|
|
|
|
|
|
|
|
def initialize(key, redis=nil)
|
|
|
|
@key = key
|
|
|
|
@redis = redis || $redis
|
2014-04-14 08:51:46 +08:00
|
|
|
@mutex = Mutex.new
|
2014-04-11 13:43:33 +08:00
|
|
|
end
|
|
|
|
|
2014-04-14 08:51:46 +08:00
|
|
|
# NOTE wrapped in mutex to maintain its semantics
|
|
|
|
def synchronize
|
|
|
|
@mutex.lock
|
|
|
|
while !try_to_get_lock
|
|
|
|
sleep 0.001
|
|
|
|
end
|
|
|
|
|
|
|
|
yield
|
|
|
|
|
|
|
|
ensure
|
|
|
|
@redis.del @key
|
|
|
|
@mutex.unlock
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2014-04-11 13:43:33 +08:00
|
|
|
def try_to_get_lock
|
2014-04-14 08:51:46 +08:00
|
|
|
got_lock = false
|
|
|
|
if @redis.setnx @key, Time.now.to_i + 60
|
|
|
|
@redis.expire @key, 60
|
|
|
|
got_lock = true
|
2014-04-11 13:43:33 +08:00
|
|
|
else
|
|
|
|
begin
|
2014-04-14 08:51:46 +08:00
|
|
|
@redis.watch @key
|
|
|
|
time = @redis.get @key
|
2014-04-11 13:43:33 +08:00
|
|
|
if time && time.to_i < Time.now.to_i
|
2014-04-14 08:51:46 +08:00
|
|
|
got_lock = @redis.multi do
|
|
|
|
@redis.set @key, Time.now.to_i + 60
|
2014-04-11 13:43:33 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
ensure
|
2014-04-14 08:51:46 +08:00
|
|
|
@redis.unwatch
|
2014-04-11 13:43:33 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2014-04-14 08:51:46 +08:00
|
|
|
got_lock
|
2014-04-11 13:43:33 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|