C# StackExchange.Redis 模糊删除 模糊查找
/// <summary> /// 模糊查找 /// </summary> /// <param name="key"></param> public List<XJDataDll.Tag.Point> SelectTags(string pattern) { List<XJDataDll.Tag.Point> result = new List<XJDataDll.Tag.Point>(); try { var redisResult = _Redisconnection.GetDatabase().ScriptEvaluate(LuaScript.Prepare( //Redis的keys模糊查询: " local res = redis.call('KEYS', @keypattern) " + " return res "), new { @keypattern = pattern }); if (!redisResult.IsNull) { RedisKey[] preSult = (RedisKey[])redisResult; var Tags = _Redisconnection.GetDatabase().StringGet(preSult); if (Tags != null) { result = Tags.Select(o => XJDataDll.Json.DataJsonSerializer.JsonToObject<XJDataDll.Tag.Point>(o.ToString())).ToList(); } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (result == null) { result = new List<XJDataDll.Tag.Point>(); } } return result; }
/// <summary> /// 模糊删除 /// </summary> /// <param name="key"></param> public void LikeRemove(string pattern) { try { var redisResult = _Redisconnection.GetDatabase().ScriptEvaluate(LuaScript.Prepare( //Redis的keys模糊查询: " local res = redis.call('KEYS', @keypattern) " + " return res "), new { @keypattern = pattern }); if (!redisResult.IsNull) { RedisKey[] preSult = (RedisKey[])redisResult; _Redisconnection.GetDatabase().KeyDelete(preSult); } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
StackExchange.Redis 模糊查询和删除
初始化连接对象
_connectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString; _connMultiplexer = ConnectionMultiplexer.Connect(_connectionString); _db = _connMultiplexer.GetDatabase(db);
通过 keys或scan查找出匹配的key,StackExchange.Redis 中调用 keys/scan/size/flush/save/集群 等命令须使用 IServer 对象
_server = _connMultiplexer.GetServer(_connMultiplexer.GetEndPoints()[0]); //默认一个服务器 var pattern = "BUIK_201710*"; var keys = _server.Keys(database: _db.Database, pattern: pattern); //StackExchange.Redis 会根据redis版本决定用keys还是scan(>2.8) return _db.KeyDelete(keys.ToArray()); //删除一组key
如果数据量很大(比如几十万个key),以上操作会很慢,甚至超时,原因未知,因为通过命令执行keys是很快的
为了提高效率,可以通过Lua脚本进行模糊查询的批量操作
var pattern = "BUIK_201710*"; var redisResult = await _db.ScriptEvaluateAsync(LuaScript.Prepare( //Redis的keys模糊查询: " local res = redis.call('KEYS', @keypattern) " + " return res "), new { @keypattern = pattern }); if (!redisResult.IsNull) { _db.KeyDelete((string[])redisResult); //删除一组key }
当然也可以通过脚本执行删除,不赘述,参考:https://www.cnblogs.com/skig/p/redis-lua-batch.html
标签:C#,pattern,模糊,Redis,redisResult,keys,var From: https://www.cnblogs.com/Leo_wl/p/17373919.html