redis

Set a key if it does not exist, otherwise return its value


I don't seem to find a command in Redis to achieve the following:

Set a key if it does not exist, otherwise return its value

Is there any way of achieving this in one transaction?


Solution

  • One transaction? sure. One command? Don't think so.

    Within a transaction, use SETNX to set a key if it does not exist, then get the value.

    MULTI
    SETNX keyName value
    GET keyName
    EXEC