user462455
user462455

Reputation: 13588

Set a value to a key with ttl

Is it possible to setnx a key with a value and a ttl in single command in redis

I am trying to implement locking in redis and http://redis.io/commands/hsetnx seems like the best way to do that. It is atomic and returns 0 if a key is already present. Is it possible to HSETNX with TTL

e.g.

HSETNX myhash mykey "myvalue" 10

#and key expires after 10 seconds, and a subsequent HSETNX after 10 seconds returns a value 1 i.e. it behaves as if mykey is not present in myhash

Upvotes: 3

Views: 6325

Answers (1)

Leonid Beschastny
Leonid Beschastny

Reputation: 51460

The main problem is that Redis have no support for fields expiration in hashmaps.

You can only expire the entire hashmap by calling EXPIRE on myhash.

So, you should reconsider using ordinary Redis strings instead of hashmaps, because they support SETEX operation.

It'll work fine unless you want to take advantage of using HGETALL, HKEYS or HVALS on your hashmap myhash:

SETEX mynamespace:mykey 10 "myvalue"

mynamespace is not a hashmap here, it simply a prefix, but in most cases it works just as hashmaps do. The only difference is that there is no efficient way to tell which keys are stored in the given namespace or to get them all with a single command.

Upvotes: 4

Related Questions