How to set expiration time for hmset in node redis?
Asked Answered
M

3

20

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

Mamiemamma answered 26/12, 2018 at 11:0 Comment(0)
G
31

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)
Gunfire answered 26/12, 2018 at 13:5 Comment(3)
The thing is those are 2 commands, means the entire operation is not atomic. If, for whatever reason, client.expire() will not be processed, you'll end up with a record that would never expire. It would be great would Redis have a single command for both setting a hash and defining its expiration time all at once.Frankfort
Yes, but you can use a MULTI/EXEC block or a Lua script to ensure atomicity in lieu of a dedicated command.Gunfire
@StasKorzovsky I need to set expiry for my key set in hash via hmset. Can you help me how we can do it ? Above method is showing me TTL for key as -1.Partida
M
4

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.

Marasco answered 8/9, 2021 at 12:19 Comment(1)
Thanks, worth to mention that to ensure atomicity you can use multi() instead of pipeline() (As stated in the article you linked)Bimetallism
L
-3

A good way to ensure that expiration is set after the key is to wrap the process in an ES6 async function:

async function (keyString, token, ttl) {
        return new Promise(function(resolve, reject) {
            redisClient.hmset("auth", keyString, token, function(error,result) {
                if (error) {
                    reject(error);
                } else {
                    redisClient.expire(keyString, ttl)
                    resolve(result);
                }
            });
        });
    }
Limbate answered 12/6, 2019 at 15:58 Comment(1)
It doesn't help you to ensure atomicity, which is discussed above.Tradesman

© 2022 - 2024 — McMap. All rights reserved.