Last active
August 29, 2015 14:06
-
-
Save phstc/f5c86887910ba13edf60 to your computer and use it in GitHub Desktop.
Easy distributed locks using Redis - https://wombat.co/blog/easy_distributed_locks_using_redis/
This file contains 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
module Wombat | |
# @example Lock while executing `do_something` or expire in 10 seconds | |
# Wombat::Mutex.exclusive 'my_key', 10 do | |
# do_something | |
# end | |
# | |
class Mutex | |
class << self | |
# @param key [String] the lock key | |
# @param ttl [Fixnum] time to live in seconds | |
# @yield the block to be exclusively executed | |
def exclusive(key, ttl, &block) | |
if lock(key, ttl) | |
begin | |
yield | |
rescue => e | |
Wombat.logger.error(e) | |
ensure | |
unlock(key) | |
end | |
end | |
end | |
# @param key [String] the lock key | |
# @param ttl [Fixnum] time to live in seconds | |
def lock(key, ttl) | |
locked, _ = Wombat.redis.multi do | |
Wombat.redis.setnx mutex_key(key), Thread.current.object_id | |
Wombat.redis.expire mutex_key(key), ttl | |
end | |
locked | |
end | |
# @param key [String] the lock key | |
def unlock(key) | |
!!Wombat.redis.del(mutex_key(key)) | |
end | |
private | |
def mutex_key(key) | |
"#{key}_mutex_lock" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment