Background
I have an atomic operation and I need to use a lock to prevent other clients from reading an unstable value.
- Platform: Node 10.1.0
- Library: redis
Solution
According to the official documentation, the solution for this is to use WATCH
together with MULTI
:
Problem
Now, the usage of MULTI
is documented and I have a general idea on how I can use it.
var redis = require( "redis" );
var bluebird = require( "bluebird" );
var client = redis.createClient();
var multi = client.multi();
multi.hsetAsync( "test", "array", "[1, 2]" );
multi.hgetAsync( "test", "array" );
multi.execAsync( ).then( console.log ); // [ 0, "[1, 2]" ]
I understand that this is the correct implementation of multi. First i need to create a client, and then I create a multi query.
I understand that multi
and client
share the same interface, but it is also not clear what benefits ( if any ) I have from using hgetAsync
instead of hget
in a multi
query, since I assume that all that multi does is adding said requests to a queue synchronously ( therefore I shouldn't need the Async vartiant ).
Upon calling multi.execAsync( )
the execution of the query will happen atomically.
But I don't get how WATCH
is supposed to enter here. I couldn't find any reference to it in the documentation, not anything regarding the optimist lock system that REDIS has.
Questions
So I have the following questions:
- Is
WATCH
supported withMULTI
? - If so, can you share a code snippet ?
- Does it make sense in this example to use
multi.hgetAsync( "test", "array" );
instead ofmulti.hget( "test", "array" );
?