Ganesh Satpute
Ganesh Satpute

Reputation: 3941

Redis: Raise error if key exist

I'm developing an application where I'm putting some key in Redis. If the given key exists Redis should raise an error.

[Due to concurrency issues, I can't read the key and then update the Redis. I can't write a piece of critical code either. ]

Can Redis be configured in such a way?

Upvotes: 0

Views: 2891

Answers (1)

Not_a_Golfer
Not_a_Golfer

Reputation: 49187

Redis cannot be configured to raise an error, but you can set your new key such that if it already exists, nothing will happen, using the SETNX command. The return value of SETNX is 1 if the key did not exist and we set its value, and 0 if it existed and we could not set a new value.

For example:

127.0.0.1:6379> SETNX foo bar
(integer) 1 
127.0.0.1:6379> get foo
"bar"

127.0.0.1:6379> SETNX foo baz
(integer) 0
127.0.0.1:6379> get foo
"bar"

Notice that calling SETNX again returned 0, and the value in the key did not change.

Upvotes: 1

Related Questions