Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set expiration time for hmset in node redis?

I used to do client.setex(key, 900, value) for storing single key-value.
But, I want to store an object with expiration time.
I come up with function hmset, but I don't know how to make expiration time.
I want to use it to store the context and the text of current chat in conversation.
Please help

like image 739
Terry Djony Avatar asked Dec 26 '18 11:12

Terry Djony


People also ask

How do I expire a list in Redis?

As noted in the accepted answer, expiration in Redis is only performed at key-level - nested elements cannot be expired. To "expire" items, call ZREMRANGEBYSCORE from -inf and the current epoch minus 24 hours.

Does Redis automatically delete expired keys?

After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology. The timeout will only be cleared by commands that delete or overwrite the contents of the key, including DEL , SET , GETSET and all the *STORE commands.

What is Hmset in Redis?

Redis HMSET command is used to set the specified fields to their respective values in the hash stored at the key. This command overwrites any existing fields in the hash. If the key does not exist, a new key holding a hash is created.


2 Answers

To expire a Hash (or any other Redis key for that matter), call the EXPIRE command. In your case:

client.hmset(key, ...
client.expire(key, 9000)
like image 141
Itamar Haber Avatar answered Oct 22 '22 03:10

Itamar Haber


Since, hmset is deprecated (see this), you can use hset with expire using pipeline.

pipe = client.pipeline()
pipe.hset(key, mapping=your_object).expire(duration_in_sec).execute()

# for example:
pipe.hset(key, mapping={'a': 1, 'b': 2}).expire(900).execute()

Note: Pipeline does not ensure atomicity.

like image 22
Deepam Gupta Avatar answered Oct 22 '22 01:10

Deepam Gupta