Class: RedisRds::Mutex

Inherits:
String show all
Defined in:
lib/redis_rds/mutex.rb

Constant Summary collapse

DEFAULT_EXPIRY =
60.seconds

Instance Attribute Summary collapse

Attributes inherited from Object

#redis_key

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from String

#append, #decr, #decrby, #get, #incr, #incrby, #length, #set, #setex, #setnx

Methods inherited from Object

configure, connection, #connection, #delete, #dump, #exists?, #expire, #expireat, flushdb, #namespace, #persist, #pttl, #ttl, #type

Constructor Details

#initialize(id, expiry = DEFAULT_EXPIRY, owner = '') ⇒ Mutex

Returns a new instance of Mutex.



7
8
9
10
11
12
13
# File 'lib/redis_rds/mutex.rb', line 7

def initialize(id, expiry = DEFAULT_EXPIRY, owner = '')
  super("#{namespace}:mutex:#{id}")

  @id = id
  @expiry = expiry
  @owner = owner.blank? ? generate_owner : owner
end

Instance Attribute Details

#expiryObject (readonly)

Returns the value of attribute expiry.



5
6
7
# File 'lib/redis_rds/mutex.rb', line 5

def expiry
  @expiry
end

#idObject (readonly)

Returns the value of attribute id.



5
6
7
# File 'lib/redis_rds/mutex.rb', line 5

def id
  @id
end

Class Method Details

.unserialize(serialized) ⇒ Object



51
52
53
# File 'lib/redis_rds/mutex.rb', line 51

def unserialize(serialized)
  return self.new(*serialized)
end

Instance Method Details

#lockObject



15
16
17
18
# File 'lib/redis_rds/mutex.rb', line 15

def lock
  connection.set(@redis_key, @owner, ex: @expiry, nx: true)
  return locked?
end

#locked?Boolean Also known as: owned?

Returns:

  • (Boolean)


20
21
22
# File 'lib/redis_rds/mutex.rb', line 20

def locked?
  return connection.get(@redis_key) == @owner
end

#releaseObject



25
26
27
# File 'lib/redis_rds/mutex.rb', line 25

def release
  self.delete if owned?
end

#serializeObject



29
30
31
# File 'lib/redis_rds/mutex.rb', line 29

def serialize
  [@id, @expiry, @owner]
end

#synchronizeObject



33
34
35
36
37
38
39
40
41
# File 'lib/redis_rds/mutex.rb', line 33

def synchronize
  if self.lock
    begin
      yield if block_given?
    ensure
      self.release
    end
  end
end