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
Asked
Active
Viewed 2.5k times
20

Terry Djony
- 1,975
- 4
- 23
- 41
3 Answers
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)

Itamar Haber
- 47,336
- 7
- 91
- 117
-
11The 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. – Stas Korzovsky Apr 01 '19 at 05:58
-
3Yes, but you can use a `MULTI/EXEC` block or a Lua script to ensure atomicity in lieu of a dedicated command. – Itamar Haber Apr 06 '19 at 12:55
-
@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. – Vipulw Apr 21 '21 at 12:07
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()

Deepam Gupta
- 2,374
- 1
- 30
- 33
-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);
}
});
});
}

Dan Burkhardt
- 13
- 2