我们正在使用 .NET 核心的 Microsoft 分布式缓存实现。参见 https://learn.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1获取更多信息。
现在我们可以通过下面的代码得到一个key。
var cacheKey = "application:customer:1234:profile";
var profile = _distributedCache.GetString(cacheKey);
我想做的是执行以下操作:
var cacheKey = "application:customer:1234:*";
var customerData = _distributedCache.GetString(cacheKey);
这样我们就可以用这个模式得到以下键:
- 应用程序:客户:1234:个人资料
- 应用程序:客户:1234:订单
- 应用程序:客户:1234:发票
- 应用程序:客户:1234:付款
无法使用任何通配符或不使用通配符来完成这项工作。有没有不实现另一个 Redis nuget 包的解决方案?
最佳答案
IDistributeCache
接口(interface)不支持此操作。它旨在获取/设置特定键,而不是返回一系列键。如果你需要做这样的事情,你需要进入底层商店,即 Redis。好消息是您不需要任何额外的东西:支持 Redis IDistributedCache
实现所需的相同 StackExchange.Redis
库还提供了一个您可以直接使用的客户端.
特别是对于您的场景,您需要一些代码,例如:
var server = _redis.GetServer(someServer);
foreach(var key in server.Keys(pattern: cacheKey)) {
// do something
}
这里,_redis
是ConnectionMultiplexer
的一个实例。这应该已经在您的服务集合中注册,因为 Redis IDistributedCache
实现使用了它。因此,您可以将其注入(inject)到 Controller 或其他存在此代码的类中。
someServer
变量是对您的一个 Redis 服务器的引用。您可以通过 _redis.GetEndpoints()
获取所有已注册的 Redis 服务器。这将返回服务器的 IEnumerable
,您可以从中选择或枚举服务器。此外,您可以通过传递主机字符串和端口直接连接到特定服务器:
var server = _redis.GetServer("localhost", 6379);
不过请注意,Keys()
将导致在 Redis 服务器上发出 SCAN 或 KEYS 命令。使用哪个取决于服务器版本,但两者都相当低效,因为必须查看整个 key 空间。建议您不要在生产中使用它,或者如果必须,请在从属服务器上发布它。
考虑到 SCAN/KEYS 的复杂性和固有的低效率,从技术上回答了你的问题,你最好做一些像这样的事情:
var cacheKeyPrefix = "application:customer:1234";
var profile = _distributedCache.GetString($"{cacheKeyPrefix}:Profile");
var orders = _distributedCache.GetString($"{cacheKeyPrefix}:Orders");
var invoices = _distributedCache.GetString($"{cacheKeyPrefix}:Invoices");
var payments = _distributedCache.GetString($"{cacheKeyPrefix}:Payments");
这最终会更快,并且不需要任何特殊的东西。
关于asp.net-core - Microsoft Distributed Redis Cache - 根据模式获取键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52985222/