Skip to content

Instantly share code, notes, and snippets.

@phstc
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phstc/f5c86887910ba13edf60 to your computer and use it in GitHub Desktop.
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/
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