Reputation: 25336
In redis there is a SETEX
command that allows me to set a key that expires, is there a multi-set version of this command that also has a TTL?
both MSET
and MSETNX
commands do not have such an option.
Upvotes: 59
Views: 33352
Reputation: 133
As of Aug 2022, this action is not possible and probably will never be as mentioned in the comments here.
I have found a good solution (in my opinion) which is the fastest I've found.
My solution was using hmset
for storing the keys, and afterwards using expire
on the hash key.
This will set the ttl for the hash and therefore for all the keys in it.
This solution isn't perfect! But considering the other solutions and the lack of options with mset, this is a solid solution which helped me solve this problem.
Upvotes: 1
Reputation: 1413
There is an issue for it back to 2012. For people who are wondering why they're not implement it.
Unfortunately, we're not going to add more commands that can work on multiple keys because they are inherently difficult to distribute. Instead, explicitly calling EXPIRE for every key you want to expire is much easier to distribute (you can route every command to a different server if needed). If you want to EXPIRE keys atomically, you can wrap multiple calls in a MULTI/EXEC block.
BTW, if the transaction is not required, try using pipeline instead of MULTI/EXEC
for better performance.
Pipelining is not just a way to reduce the latency cost associated with the round trip time, it actually greatly improves the number of operations you can perform per second in a given Redis server.
Upvotes: 11
Reputation: 1318
I was also looking for this kind of operation. I didn't find anything, so I did it with MULTI/EXEC:
MULTI
expire key1
expire key2
expire key3
EXEC
Upvotes: 21
Reputation: 653
That's sad we cant set expire with mset, ahead a solution for who is working with nodejs and redis lib:
// expires the key at next mid-night
let now = moment()
let endOfDay = moment().endOf('day')
let timeToLiveInSeconds = endOfDay.diff(now, 'seconds')
redisClient.expire(keyName, timeToLiveInSeconds)
I hope it helps
Upvotes: -1