Skip to content

Instantly share code, notes, and snippets.

@yogin16
Last active July 4, 2018 09:50
Show Gist options
  • Save yogin16/931a354933e41c14fca9f6113497db20 to your computer and use it in GitHub Desktop.
Save yogin16/931a354933e41c14fca9f6113497db20 to your computer and use it in GitHub Desktop.
Lua script for cleaning Spring's Redis cache (@Cacheable)
-- $ ./redis-cli --eval cleanSpringRedisCache.lua <CACHE_NAME>
local logtable = {}
local function logit(msg)
logtable[#logtable+1] = msg
end
local cacheName=KEYS[1]..'~keys'
logit('Cache: '..cacheName)
local cacheValues=redis.call("zrevrange", cacheName, 0, 100)
for i, key in ipairs(cacheValues) do
logit('Key: '..key)
redis.call("zrem", cacheName, key)
redis.call("del", key)
end
return logtable
@yogin16
Copy link
Author

yogin16 commented Jan 15, 2018

Enhanced further for complete pagination

-- $ ./redis-cli --eval cleanSpringCache.lua HIERARCHY HIERARCHY_NAME
local logtable = {}

local function logit(msg)
    logtable[#logtable+1] = msg
end

local batch = 100

for i, keyName in ipairs(KEYS) do
    local cacheName = keyName .. '~keys'
    logit('Cache: ' .. cacheName)

    local hasMore = true
    while hasMore do
        local cacheValues = redis.call("zrevrange", cacheName, 0, batch)
        local count = 0
        for i, key in ipairs(cacheValues) do
            logit('Key: ' .. key)
            redis.call("zrem", cacheName, key)
            redis.call("del", key)
            count = count + 1
        end
        hasMore = (count >= batch)
    end
end

return logtable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment