Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis get or create?

Tags:

redis

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?

like image 333
slezica Avatar asked Oct 23 '25 19:10

slezica


2 Answers

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

like image 70
Gagan Saksena Avatar answered Oct 26 '25 12:10

Gagan Saksena


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
like image 25
slezica Avatar answered Oct 26 '25 13:10

slezica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!