MST

星途 面试题库

面试题:Redis中TTL命令在复杂场景下的键生存时间管理

在一个电商系统的Redis缓存中,有大量以'product:商品ID'格式命名的键,这些键用于缓存商品的详细信息且都设置了生存时间。现在需要编写一个脚本(可以使用Lua脚本),批量获取这些键剩余的生存时间,并将生存时间小于10秒的键筛选出来,简述实现思路并给出关键代码片段。
47.7万 热度难度
数据库Redis

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 首先,使用SCAN命令遍历Redis中所有以product:开头的键。
  2. 对每个遍历到的键,使用TTL命令获取其剩余生存时间。
  3. 筛选出剩余生存时间小于10秒的键。

关键代码片段(Lua脚本)

local keys = {}
local cursor = "0"
local pattern = "product:*"
local result = {}

-- 使用SCAN命令遍历所有以product:开头的键
repeat
    local scanResult = redis.call('SCAN', cursor, 'MATCH', pattern)
    cursor = scanResult[1]
    local currentKeys = scanResult[2]
    for _, key in ipairs(currentKeys) do
        local ttl = redis.call('TTL', key)
        if ttl < 10 and ttl > -1 then
            table.insert(result, key)
        end
    end
until cursor == "0"

return result

在实际使用中,可以通过Redis客户端调用该Lua脚本,例如在Python中使用redis - py库:

import redis

r = redis.Redis(host='localhost', port=6379, db = 0)
script = """
local keys = {}
local cursor = "0"
local pattern = "product:*"
local result = {}
repeat
    local scanResult = redis.call('SCAN', cursor, 'MATCH', pattern)
    cursor = scanResult[1]
    local currentKeys = scanResult[2]
    for _, key in ipairs(currentKeys) do
        local ttl = redis.call('TTL', key)
        if ttl < 10 and ttl > -1 then
            table.insert(result, key)
        end
    end
until cursor == "0"
return result
"""
sha = r.script_load(script)
result = r.evalsha(sha, 0)
print(result)