我有一个格式的密钥:
Error.1
Error.24
Error.32
使用StackExchange.Redis
,我如何在与KeyDelete
格式匹配的所有密钥上Error.
?
另一个答案我见过LUA脚本:
EVAL "return redis.call('del', unpack(redis.call('keys', ARGV[1])))" 0 Error.*
但我不确定如何使用Database.ScriptEvaluate()
答案 0 :(得分:4)
只需获取与模式匹配的所有键,迭代并删除,如下所示:
using (var redisConnection = ConnectionMultiplexer.Connect(...))
{
var server = redisConnection.GetServer(endpoint:...);
if (server != null)
{
foreach (var key in server.Keys(pattern: "Error.*"))
{
redisConnection.Database.KeyDelete(key);
}
}
}
稍后编辑:
设置Redis连接的示例:https://gist.github.com/cristipufu/9ad47caf3dba60d712484d0c880597b9
应该存储和重用多路复用器,而不是每次都处理和重新创建多路复用器。 https://stackexchange.github.io/StackExchange.Redis/Basics
答案 1 :(得分:2)
Redis.StackExchange v2.1.0-preview.23及更高版本中提供了通过IAsyncEnumerable
进行 C#异步流传输的新版本。
注意:如果Redis实例支持该功能,则此版本使用SCAN而不是KEYS。这是巨大的性能提升。您还应该确保您的ConnectionMultiplexer
实例是单例-即在应用程序生命周期中使用的同一实例。
using Microsoft.Extensions.Caching.Distributed;
using StackExchange.Redis;
private readonly IDistributedCache _cache;
private readonly IConnectionMultiplexer _connectionMultiplexer;
public CacheRepository(IDistributedCache cache, IConnectionMultiplexer connectionMultiplexer)
{
_cache = cache;
_connectionMultiplexer = connectionMultiplexer;
}
public async Task RemoveWithWildCardAsync(string keyRoot)
{
if (string.IsNullOrWhiteSpace(keyRoot))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(keyRoot));
// get all the keys* and remove each one
await foreach (var key in GetKeysAsync(keyRoot + "*"))
{
await _cache.RemoveAsync(key);
}
}
public async IAsyncEnumerable<string> GetKeysAsync(string pattern)
{
if (string.IsNullOrWhiteSpace(pattern))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(pattern));
foreach (var endpoint in _connectionMultiplexer.GetEndPoints())
{
var server = _connectionMultiplexer.GetServer(endpoint);
await foreach (var key in server.KeysAsync(pattern: pattern))
{
yield return key.ToString();
}
}
}
public IEnumerable<RedisFeatures> GetRedisFeatures()
{
foreach (var endpoint in _connectionMultiplexer.GetEndPoints())
{
var server = _connectionMultiplexer.GetServer(endpoint);
yield return server.Features;
}
}