使用StackExchange.Redis沒有直接相關的方法進行模糊查詢的批量刪除和修改操作,雖然可以通過Scan相關的方法進行模糊查詢,例如:HashScan("hashkey", "*key*"),然後再使用相關的方法進行相關的批量操作,但是如果緩存數據量比較大,效率低下,那麼可以使用Lua腳本進行模糊查詢的批量操作:ScriptEvaluate(LuaScript.Prepare(...))。
1 var redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,allowAdmin = true"); 2 redis.GetDatabase().ScriptEvaluate(LuaScript.Prepare( 3 //Redis的keys模糊查詢: 4 " local ks = redis.call('KEYS', @keypattern) " + //local ks為定義一個局部變量,其中用於存儲獲取到的keys 5 " for i=1,#ks,5000 do " + //#ks為ks集合的個數, 語句的意思: for(int i = 1; i <= ks.Count; i+=5000) 6 " redis.call('del', unpack(ks, i, math.min(i+4999, #ks))) " + //Lua集合索引值從1為起始,unpack為解包,獲取ks集合中的數據,每次5000,然後執行刪除 7 " end " + 8 " return true " 9 ), 10 new { keypattern = "mykey*" });
1 redis.GetDatabase().ScriptEvaluate(LuaScript.Prepare( 2 " local ks = redis.call('KEYS', @keypattern) " + 3 " for i=1,#ks do " + 4 " redis.call('set', ks[i], @value) " + 5 " end " + 6 " return true "), 7 new { keypattern = "mykey*", value = "setval" });
1 redis.GetDatabase().ScriptEvaluate(LuaScript.Prepare( 2 " local ks = redis.call('hkeys', @hashid) " + 3 " local fkeys = {} " + 4 " for i=1,#ks do " + 5 //使用string.find進行匹配操作 6 " if string.find(ks[i], @keypattern) then " + 7 " fkeys[#fkeys + 1] = ks[i] " + 8 " end " + 9 " end " + 10 " for i=1,#fkeys,5000 do " + 11 " redis.call('hdel', @hashid, unpack(fkeys, i, math.min(i+4999, #fkeys))) " + 12 " end " + 13 " return true " 14 ), 15 new { hashid = "hkey", keypattern = "^mykey" }); //keypattern為可使用正則表達式
1 redis.GetDatabase().ScriptEvaluate(LuaScript.Prepare( 2 " local ks = redis.call('hkeys', @hashid) " + 3 " local fkeys = {} " + 4 " for i=1,#ks do " + 5 " if string.find(ks[i], @keypattern) then " + 6 " fkeys[#fkeys + 1] = ks[i] " + 7 " end " + 8 " end " + 9 " for i=1,#fkeys do " + 10 " redis.call('hset', @hashid, fkeys[i], @value) " + 11 " end " + 12 " return true " 13 ), 14 new { hashid = "hkey", keypattern = "^key", value = "hashValue" }); //keypattern為可使用正則表達式
1 redis.GetDatabase().ScriptEvaluate(LuaScript.Prepare( 2 " local ks = redis.call('smembers', @keyid) " + 3 " local fkeys = {} " + 4 " for i=1,#ks do " + 5 " if string.find(ks[i], @keypattern) then " + 6 " fkeys[#fkeys + 1] = ks[i] " + 7 " end " + 8 " end " + 9 " for i=1,#fkeys,5000 do " + 10 " redis.call('srem', @keyid, unpack(fkeys, i, math.min(i+4999, #fkeys))) " + 11 " end " + 12 " return true " 13 ), 14 new { keyid = "setkey", keypattern = "^myval" }); //keypattern為可使用正則表達式
從 Redis 2.6.0 版本開始,才可通過內置的 Lua 解釋器,使用 EVAL 命令對 Lua 腳本進行求值。