From several servers I would like to add keys like doc:1 and then doc:2 etc.
Now in order that the different servers do not try to add to, say, doc:2 at the same time, I thought there is some mechanism like "add to doc:{index}" and the index gets automatically bumped.
Is there some way to make that work?
2
Answers
You could use a distributed lock and have the winner write
docs
You could use a key which you increment on every addition: the
INCR
command does just that, atomically, and returns the incremented value which you can use to generate the new key name.Update: in the event you want the whole set of operations (incrementing the counter and setting the value) to be atomic, you can execute a Lua script instead:
Explanation:
Execute
INCR counter
and store the result in thevalue
variable.Execute
SET
against the key named after the concatenation ofdoc:
and thevalue
variable using the data passed through the firstEVAL
argument – in our case foobar.Finally, should you need to return the incremented counter value to the caller just append a final
return value;
block to the script.