Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a value to a key with ttl

Tags:

redis

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
like image 592
user462455 Avatar asked Jan 24 '26 19:01

user462455


1 Answers

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.

like image 50
Leonid Beschastny Avatar answered Jan 27 '26 14:01

Leonid Beschastny