[英]Get all keys from Redis Cache database
我正在使用 Redis 缓存进行缓存(特别是stackexchange.Redis C# driver
。想知道是否有任何方法可以随时获取缓存中可用的所有键。我的意思是我可以在 ASP.NET cache
对象中做的类似事情(下面的代码示例)
var keys = Cache.GetEnumerator();
while(keys.MoveNext())
{
keys.Key.ToString() // Key
}
Redis 文档讨论了 KESY 命令,但stackexchange.Redis
有该命令的实现。
通过connection.GetDataBase()
实例进行调试,我没有看到任何方法/属性。
任何的想法?
您需要的功能在 IServer 接口下,可以通过以下方式访问:
ConnectionMultiplexer m = CreateConnection();
m.GetServer("host").Keys();
请注意,在 2.8 版之前的 redis 服务器将使用您提到的 KEYS 命令,并且在某些情况下它可能会非常慢。 但是,如果您使用 redis 2.8+ - 它将改用 SCAN 命令,这样性能更好。 还要确保您确实需要获得所有密钥,在我的实践中,我从未需要过这个。
string connectionString = "my_connection_string";
ConfigurationOptions options = ConfigurationOptions.Parse(connectionString);
ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(options);
IDatabase db = connection.GetDatabase();
EndPoint endPoint = connection.GetEndPoints().First();
RedisKey[] keys = connection.GetServer(endPoint).Keys(pattern: "*").ToArray();
尝试使用此代码片段,它对我有用:
IServer server = Connection.GetServer("yourcache.redis.cache.windows....", 6380);
foreach (var key in server.Keys())
{
Console.WriteLine(key);
}
您需要 db 来区分在哪里寻找密钥。 所以MTZ4答案的最后一行变成了:
RedisKey[] keys = connection.GetServer(endPoint).Keys(database: db.Database, pattern: "*").ToArray();
其中 db.Database 是您要查询的 Redis 数据库的数字标识符。
ASP.NET 核心 3.1
将以下packages
添加到您的.csproj
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="3.1.15" />
<PackageReference Include="StackExchange.Redis.Extensions.AspNetCore" Version="7.0.1" />
<PackageReference Include="StackExchange.Redis.Extensions.Core" Version="7.0.1" />
<PackageReference Include="StackExchange.Redis.Extensions.Newtonsoft" Version="7.0.1" />
</ItemGroup>
在Startup.cs
中,您可以通过这种方式注册准备注入工作流代码的Redis Client
。
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ... other registrations
// Used By : Sample Below : RedisCacheHelperController (Method 1 Only)
services.AddSingleton<IConnectionMultiplexer>(
ConnectionMultiplexer.Connect(DbHelper.GetRedisConnectionHost(Options.IsDevDb()))
);
// Used By : Sample Below : DistributedCacheController (Method 2 Only)
services.AddStackExchangeRedisCache(options =>
options.Configuration = DbHelper.GetRedisConnectionHost(Options.IsDevDb())
);
// ... other registrations
}
}
注意:
DbHelper.GetRedisConnectionHost(Options.IsDevDb()) :>>> 是我根据我的环境为我的 Redis 实例解析连接信息/字符串的方法。 你可以在这里有自己的方式,或者你可以在这里硬编码,如果你想开始。
方法一
因此,有了上述内容,就可以将 Redis IConnectionMultiplexer
注入您的Controllers
或Services
。
public class RedisCacheHelperController : ControllerBase
{
private readonly IConnectionMultiplexer multiplexer;
public RedisCacheHelperController(IConnectionMultiplexer multiplexer)
{
this.multiplexer = multiplexer;
}
}
以下是演示如何使用IConnectionMultiplexer
的帮助程序 API。
public class RedisCacheHelperController : ControllerBase
{
private readonly IConnectionMultiplexer multiplexer;
public RedisCacheHelperController(IConnectionMultiplexer multiplexer)
{
this.multiplexer = multiplexer;
}
[HttpGet("{key}")]
public async Task<IActionResult> GetCacheByKey([FromRoute] string key)
{
var responseContent = await multiplexer.GetDatabase().StringGetAsync(key);
return Content(
responseContent,
Constants.ContentTypeHeaderValueJson // "application/json"
);
}
[HttpPost("{key}")]
public async Task<IActionResult> PostCacheByKey([FromRoute] string key, [FromBody] object data)
{
var requestContent = data.Json(); // JsonConvert.SerializeObject(data)
await multiplexer.GetDatabase().StringSetAsync(key, requestContent);
return Ok(key);
}
[HttpDelete("{key}")]
public async Task<IActionResult> DeleteCacheByKey([FromRoute] string key)
{
await multiplexer.GetDatabase().KeyDeleteAsync(key);
return Ok(key);
}
[HttpGet("CachedKeys")]
public IActionResult GetListCacheKeys([FromQuery] [DefaultValue("*")] string pattern)
{
var keys = multiplexer
.GetServer(multiplexer
.GetEndPoints()
.First())
.Keys(pattern: pattern ?? "*")
.Select(x => x.Get());
return Ok(keys);
}
// ... could have more Reids supported operations here
}
现在,上面是use-case
,你想访问Redis Client
,做更多Reids
具体的东西。 我们在上面的.csproj
包含的Microsoft.Extensions.Caching.StackExchangeRedis
包支持将Reids
注册并作为IDistributedCache
注入。 接口IDistributedCache
由Microsoft
定义,并通过不同的分布式缓存解决方案支持基本/通用功能,其中Redis
就是其中之一。
这意味着如果您的目的仅限于set
和/或get
缓存作为key-value pair
,您更愿意在下面的Method 2
中以这种方式执行此操作。
方法二
public class DistributedCacheController : ControllerBase
{
private readonly IDistributedCache distributedCache;
public DistributedCacheController(IDistributedCache distributedCache)
{
this.distributedCache = distributedCache;
}
[HttpPost("{key}")]
public async Task<IActionResult> PostCacheByKey([FromRoute] string key, [FromBody] object data)
{
var requestContent = data.Json(); // JsonConvert.SerializeObject(data)
await distributedCache.SetStringAsync(key, requestContent);
return Ok(key);
}
[HttpGet("{key}")]
public async Task<IActionResult> GetCacheByKey([FromRoute] string key)
{
var responseContent = await distributedCache.GetStringAsync(key);
if (!string.IsNullOrEmpty(responseContent))
{
return Content(
responseContent,
Constants.ContentTypeHeaderValueJson // "application/json"
);
}
return NotFound();
}
[HttpDelete("{key}")]
public async Task<IActionResult> DeleteCacheByKey([FromRoute] string key)
{
await distributedCache.RemoveAsync(key);
return Ok(key);
}
}
一旦你有了你的 IDatabase 实例,我正在使用它:
var endpoints = _Cache.Multiplexer.GetEndPoints();
var server = _Cache.Multiplexer.GetServer(endpoints[0]);
var keys = server.Keys();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.