Redis Lua脚本实现指定Key驱逐策略的问题咨询
解决方案
你的脚本当前同时扫描并处理了User_DB_1:*和User_Main:*两类Key,逻辑超出了你仅删除User_DB_1:<user_id>的需求,且可能因多模式扫描的cursor复用导致遍历混乱。要实现预期效果,修改后的脚本如下:
local cursor = "0" local target_pattern = "User_DB_1:*" local total_evicted = 0 local limit = 1000 -- 单次脚本运行删除的Key上限 repeat -- 扫描匹配User_DB_1:*的Key local res = redis.call("SCAN", cursor, "MATCH", target_pattern, "COUNT", limit) cursor = res[1] local keys = res[2] for _, key in ipairs(keys) do -- 严格验证Key格式:以User_DB_1:开头,后面跟纯数字的user_id if string.match(key, "^User_DB_1:%d+$") then redis.call("DEL", key) redis.log(redis.LOG_NOTICE, "Deleted key: " .. key) total_evicted = total_evicted + 1 -- 达到删除上限时提前返回 if total_evicted >= limit then return total_evicted end end end until cursor == "0" return total_evicted
修改说明
- 移除多余扫描逻辑:删除原脚本中针对
User_Main:*的处理代码,确保只聚焦目标Key类型; - 简化模式管理:用单个变量存储匹配模式,避免多模式带来的逻辑混乱;
- 保留严格格式校验:通过
string.match(key, "^User_DB_1:%d+$")过滤掉格式不符的Key,即使SCAN因glob匹配特性出现极端情况的误返回,也不会触发删除; - 规范cursor使用:每次SCAN都基于上一次返回的cursor,保证遍历的完整性和正确性。
执行脚本的命令保持不变:
redis-cli --eval /data/redis_evication.lua
内容的提问来源于stack exchange,提问作者AbdUlRahman Mansy
相关产品推荐
相关产品推荐

