Redis get or create?

redis

Solution

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

Problem

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`?

Original source