/// /// public List SelectTags(string pattern) List result = new List(); 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(o.ToString())).ToList(); catch (Exception ex) Console.WriteLine(ex.Message); finally if (result == null) result = new List(); return result; 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);

初始化连接对象

_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

作者:Leo_wl
         
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。