How to set expiration time for hmset in node redis?

Viewed 21602

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

3 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)

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.

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);
                }
            });
        });
    }
Related