You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

修改说明

  1. 移除多余扫描逻辑:删除原脚本中针对User_Main:*的处理代码,确保只聚焦目标Key类型;
  2. 简化模式管理:用单个变量存储匹配模式,避免多模式带来的逻辑混乱;
  3. 保留严格格式校验:通过string.match(key, "^User_DB_1:%d+$")过滤掉格式不符的Key,即使SCAN因glob匹配特性出现极端情况的误返回,也不会触发删除;
  4. 规范cursor使用:每次SCAN都基于上一次返回的cursor,保证遍历的完整性和正确性。

执行脚本的命令保持不变:

redis-cli --eval /data/redis_evication.lua

内容的提问来源于stack exchange,提问作者AbdUlRahman Mansy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 10:29:52