-- Lua脚本:根据通配符删除键
-- KEYS[1]: 匹配的键的通配符
local keyPattern = KEYS[1]
local cursor = 0
local keys = {}
repeat
local result = redis.call("SCAN", cursor, "MATCH", keyPattern, "COUNT", 100)
cursor = tonumber(result[1])
local replyKeys = result[2]
for _, key in ipairs(replyKeys) do
table.insert(keys, key)
end
until cursor == 0
-- 逐个删除键
for _, key in ipairs(keys) do
redis.call("DEL", key)
end
// 根据通配符删除
// 使用lua保证原子性
func DeleteRedisKeysByPattern(conn redis.Conn, key string) error {
// 读取Lua脚本内容
luaScript := `
local cursor = 0
local keys = {}
repeat
local result = redis.call("SCAN", cursor, "MATCH", ARGV[1], "COUNT", 100)
cursor = tonumber(result[1])
local replyKeys = result[2]
for _, key in ipairs(replyKeys) do
table.insert(keys, key)
end
until cursor == 0
-- 逐个删除键
for _, key in ipairs(keys) do
redis.call("DEL", key)
end
`
// 将Lua脚本注册到Redis连接
script := redis.NewScript(0, luaScript)
// 执行Lua脚本
_, err := script.Do(conn, key)
if err != nil {
fmt.Println("Lua脚本执行失败:", err)
return err
}
return nil
}