I\'m encapsulating a complicated set of Redis commands in a MULTI transaction, but the logic in the transaction depends on values already in Redis. But all reads within a transa
You cannot, since all commands (including get) are actually executed at exec time. In this situation, the get command only returns a future object, not the actual value.
There are two ways to implement such transaction.
Using a WATCH clause
The watch clause is used to protect against concurrent updates. If the value of the variable is updated between the watch and multi clause, then the commands in the multi block are not applied. It is up to the client to attempt the transaction another time.
loop do
$redis.watch "foo"
val = $redis.get("foo")
if val == "bar" then
res = $redis.multi do |r|
r.set("foo", "baz")
end
break if res
else
$redis.unwatch "foo"
break
end
end
Here the script is a bit complex because the content of the block can be empty, so there is no easy way to know whether the transaction has been cancelled, or whether it did not take place at all. It is generally easier when the multi block returns results in all cases except if the transaction is cancelled.
Using Lua server-side scripting
With Redis 2.6 or better, Lua scripts can be executed on the server. The execution of the whole script is atomic. It can be easily implemented in Ruby:
cmd = <
This is typically much simpler than using WATCH clauses.