35

Can I set global TTL in redis? Instead of setting TTL every time I set a key.

I googled, but cannot found any clue. So it seems cannot be done?

Thanks.

Sato
  • 8,192
  • 17
  • 60
  • 115

3 Answers3

29

No, Redis doesn't have a notion of a global/default TTL and yes, you do have to set it for each key independently. However, depending on your requirements and on what you're trying to do, there may be other ways to achieve your goal. Put differently, why do you need it?

For example, if you want to use Redis as a cache and not worry about having to remove "old" items, you can get simply by setting the maxmemory_policy to allkey-lru. This will evict the least recently used keys whenever Redis' memory is exhausted.

EDIT: for more information, see the helpful links in the comments below from @arganzheng and @Kristján, as well as the inline documentation in the redis.conf configuration file.

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117
4

If you are setting a key , you can set the TTL in the same time : look at the set command

a side , you can done this by scripting (on linux like - for 60 seconds):

for k in `redis-cli --raw keys '*'` ; do redis expire $k 60;done
Philippe T.
  • 1,182
  • 7
  • 11
  • 7
    "keys" is terrible in production, because it synchronously locks up the database. Only trivially small databases can get away with this. If you want to iterate over keys, use SCAN. The other problem with this option is that it will actually refresh the TTL of all keys, so all keys will live forever, unless you make sure to run the script less often than the TTL you want to say. If you want to, say, manage web sessions, where they should expire after 30 days, you can only run the script every 31 days... – Jon Watte May 25 '17 at 22:58
2

While not being a "pure" Redis solution for this, check out this RedisGears example that achieves this purpose: https://oss.redislabs.com/redisgears/master/examples.html#automatic-expiry

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117