I want to use Redis as a random seed cache. When I want the value for a key, if nothing's there yet, I'll produce a random string and store it for later reuse.
How do I perform an atomic GET EXISTING OR SET AND RETURN THIS VALUE?
You could use SETNX to try and set the value first. Then the GET would give you the existing value or the new one you tried to set.
SETNX key value
This may return 0 or 1 if you care to know if this is a new value
It seems there is no single command that can do this. Using MULTI and WATCH:
First:
GET key
If null, then:
WATCH key
MULTI
SET key value
EXEC
If [null] (indicating the transaction aborted), the key was created in the meantime and must exist by now:
GET key
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With