-
Notifications
You must be signed in to change notification settings - Fork 228
how to set expiration and timeout for lock
Chiwen edited this page Jun 17, 2019
·
1 revision
The below example will be used to test the difference of expiration
and timeout
of redis-object lock
# in User model
def purchase(item)
self.purchase_something_lock.lock do
puts "buy a #{item}"
sleep 5
end
end
# in User model
lock :purchase_something, expiration: 3
when expiration of former process is reached, the lock will released, a latter process can obtain the lock and do the work.
example:
# execute and result
['book', 'doll'].each do |item|
Thread.new do
purchase(item)
end
end
#=> buy a book
(after 3 sec...)
#=> buy a doll
# in User model
lock :purchase_something, timeout: 3
when timeout of latter process is reached, the process will exit with a timeout exception.
# execute and result
['book', 'doll'].each do |item|
Thread.new do
begin
purchase(item)
rescue => e
puts e
end
end
end
#=> buy a book
(after 3 sec...)
#=> Redis::Lock::LockTimeout: Timeout on lock .........