54

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.

Ian
  • 24,116
  • 22
  • 58
  • 96

5 Answers5

18

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
Brad Koch
  • 19,267
  • 19
  • 110
  • 137
unreal
  • 1,259
  • 12
  • 17
7

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.

呂學洲
  • 1,123
  • 8
  • 19
1

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.

Ofirfr
  • 76
  • 1
  • 5
0
EVAL "<multi_ttl_script>" N key1 key2 ... value1 ttl1 value2 ttl2 ...
Vad
  • 4,052
  • 3
  • 29
  • 34
0

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

Fábio Magagnin
  • 605
  • 7
  • 11
  • 1
    This is a question about Redis, not about Node. I think nearly everyone that lands on this page knows the EXPIRE command exists: https://redis.io/commands/expire – kylebebak Sep 08 '21 at 19:11