从 Redis 缓存数据库中获取所有键
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 documentation talks about KESY command 但 stackexchange.Redis
有该命令的实现。
通过 connection.GetDataBase()
实例调试,我没有看到任何方法/属性。
有什么想法吗?
您需要的功能在IServer接口下,可以通过以下方式实现:
ConnectionMultiplexer m = CreateConnection();
m.GetServer("host").Keys();
请注意,在 2.8 版之前的 redis 服务器将使用您提到的 KEYS 命令,并且在某些情况下可能会非常慢。但是,如果您使用 redis 2.8+ - 它将改用 SCAN 命令,这样性能更好。还要确保您确实需要获取所有密钥,在我的实践中我从来不需要这个。
尝试使用这个代码片段,它对我有用:
IServer server = Connection.GetServer("yourcache.redis.cache.windows....", 6380);
foreach (var key in server.Keys())
{
Console.WriteLine(key);
}
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();
您需要数据库来区分在哪里寻找键。所以 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()) :>>> is my way to resolve the connection information/string for my Redis instance respective to my environment. You can have your own way here for that or you can hard-code it here if you like to begin with.
方法一
所以,有了上面的东西,就可以将 Redis IConnectionMultiplexer
注入你的 Controllers
或 Services
。
public class RedisCacheHelperController : ControllerBase
{
private readonly IConnectionMultiplexer multiplexer;
public RedisCacheHelperController(IConnectionMultiplexer multiplexer)
{
this.multiplexer = multiplexer;
}
}
下面是帮助程序 API,用于演示如何使用 IConnectionMultiplexer
。
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
并执行更多 Redis
特定内容的地方。我们在上面 .csproj
中包含的包 Microsoft.Extensions.Caching.StackExchangeRedis
支持 Reids
作为 IDistributedCache
注册和注入。接口 IDistributedCache
由 Microsoft
定义并支持 basic/common 不同分布式缓存解决方案的功能,其中 Redis
是其中之一。
意味着如果您的目的仅限于 set
and/or get
缓存作为 key-value pair
,您更愿意在 [=36= 中这样做] 下面。
方法二
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();
我正在将 Redis 缓存用于缓存目的(特别是 stackexchange.Redis C# driver
。想知道是否有任何方法可以在任何时间点获取缓存中可用的所有键。我的意思是我可以做类似的事情ASP.NET cache
对象(代码示例下方)
var keys = Cache.GetEnumerator();
while(keys.MoveNext())
{
keys.Key.ToString() // Key
}
Redis documentation talks about KESY command 但 stackexchange.Redis
有该命令的实现。
通过 connection.GetDataBase()
实例调试,我没有看到任何方法/属性。
有什么想法吗?
您需要的功能在IServer接口下,可以通过以下方式实现:
ConnectionMultiplexer m = CreateConnection();
m.GetServer("host").Keys();
请注意,在 2.8 版之前的 redis 服务器将使用您提到的 KEYS 命令,并且在某些情况下可能会非常慢。但是,如果您使用 redis 2.8+ - 它将改用 SCAN 命令,这样性能更好。还要确保您确实需要获取所有密钥,在我的实践中我从来不需要这个。
尝试使用这个代码片段,它对我有用:
IServer server = Connection.GetServer("yourcache.redis.cache.windows....", 6380);
foreach (var key in server.Keys())
{
Console.WriteLine(key);
}
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();
您需要数据库来区分在哪里寻找键。所以 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()) :>>> is my way to resolve the connection information/string for my Redis instance respective to my environment. You can have your own way here for that or you can hard-code it here if you like to begin with.
方法一
所以,有了上面的东西,就可以将 Redis IConnectionMultiplexer
注入你的 Controllers
或 Services
。
public class RedisCacheHelperController : ControllerBase
{
private readonly IConnectionMultiplexer multiplexer;
public RedisCacheHelperController(IConnectionMultiplexer multiplexer)
{
this.multiplexer = multiplexer;
}
}
下面是帮助程序 API,用于演示如何使用 IConnectionMultiplexer
。
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
并执行更多 Redis
特定内容的地方。我们在上面 .csproj
中包含的包 Microsoft.Extensions.Caching.StackExchangeRedis
支持 Reids
作为 IDistributedCache
注册和注入。接口 IDistributedCache
由 Microsoft
定义并支持 basic/common 不同分布式缓存解决方案的功能,其中 Redis
是其中之一。
意味着如果您的目的仅限于 set
and/or get
缓存作为 key-value pair
,您更愿意在 [=36= 中这样做] 下面。
方法二
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();