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
How to set expiration time for hmset in node redis?
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)
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
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()
Thanks, worth to mention that to ensure atomicity you can use
multi()
instead of pipeline()
(As stated in the article you linked) –
Bimetallism 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);
}
});
});
}
It doesn't help you to ensure atomicity, which is discussed above. –
Tradesman
© 2022 - 2024 — McMap. All rights reserved.