Skip to content

Instantly share code, notes, and snippets.

@Aschen
Created November 5, 2021 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aschen/2e8e4aeacbcf8a55356755c408434bfb to your computer and use it in GitHub Desktop.
Save Aschen/2e8e4aeacbcf8a55356755c408434bfb to your computer and use it in GitHub Desktop.
Redis: Count, print or delete keys that expires after a specified TTL

Usage:

  • redis-cli --eval clean-keys.lua <mode> <days>
  • redis-cli --eval clean-keys.lua count 1
  • redis-cli --eval clean-keys.lua print 1
  • redis-cli --eval clean-keys.lua delete 1

For example, redis-cli --eval clean-keys.lua count 2 will return the number of keys expiring in more than 2 days

local mode = KEYS[1]
local count = 0
local cursor = 0
local maxTTL = 2 * 24 * 3600 -- act on keys that expires in more 2 days
if (KEYS[2]) then
maxTTL = tonumber(KEYS[2]) * 24 * 3600
end
redis.call('SELECT', 5)
repeat
local result = redis.call("SCAN", cursor);
cursor = result[1];
local keys = result[2]
for i=1,#keys do
local key = keys[i]
local ttl = redis.call('TTL',key)
if ttl > maxTTL then
if mode == 'delete' then
redis.call('DEL', key)
end
if mode == 'print' then
print(key .. " " .. ttl)
end
count = count + 1
end
end
until cursor == "0";
return count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment