问题
Is there any way to do an atomic set only if not already set in Redis?
Specifically, I'm creating a user like "myapp:user:user_email" and want Redis to give me back an error if "user_email" is already taken, instead of silently replacing the old value. Something like declare, not replace.
回答1:
See SETNX
Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. SETNX is short for "SET if N ot e X ists".
You can check the return value. If it is 0, the key was not set, implying it already existed.
来源:https://stackoverflow.com/questions/16159092/atomic-set-only-if-not-already-set