面试题答案
一键面试实现思路
- 首先,使用
SCAN
命令遍历Redis中所有以product:
开头的键。 - 对每个遍历到的键,使用
TTL
命令获取其剩余生存时间。 - 筛选出剩余生存时间小于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)