我们正在使用.net核心的Microsoft Distrbuted Cache实现。有关更多信息,请参见https://docs.microsoft.com/en-us/aspnet/core/performance/caching/distributed?view=aspnetcore-2.1。
现在我们可以通过以下代码获取密钥。
var cacheKey = "application:customer:1234:profile";
var profile = _distributedCache.GetString(cacheKey);
我想做的是做以下事情:
var cacheKey = "application:customer:1234:*";
var customerData = _distributedCache.GetString(cacheKey);
这样我们就可以通过此模式获得以下键:
使用任何通配符或没有通配符都无法完成这项工作。没有实现另一个Redis nuget软件包的解决方案吗?
答案 0 :(得分:2)
IDistributeCache
接口不支持此功能。它旨在获取/设置特定键,而不是返回一定范围的键。如果您需要执行此类操作,则需要进入基础存储区,即Redis。好消息是您不需要其他任何东西:支持Redis StackExchange.Redis
实现所需的同一IDistributedCache
库也提供了可以直接使用的客户端。
特别是在这里的情况下,您需要一些代码,例如:
var server = _redis.GetServer(someServer);
foreach(var key in server.Keys(pattern: cacheKey)) {
// do something
}
在这里,_redis
是ConnectionMultiplexer
的实例。这已被Redis IDistributedCache
实现所利用,因此应该已经在您的服务集合中注册了。结果,您可以将其注入存在此代码的控制器或其他类中。
someServer
变量是对您的Redis服务器之一的引用。您可以通过_redis.GetEndpoints()
获取所有已注册的Redis服务器。这将返回IEnumerable
台服务器,您可以从中选择或枚举服务器。此外,您可以通过传递主机字符串和端口直接将其直接连接到特定服务器:
var server = _redis.GetServer("localhost", 6379);
但是请注意,Keys()
将导致Redis服务器上发出SCAN或KEYS命令。使用哪种方法取决于服务器版本,但是由于必须查看整个键空间,因此两者效率都相当低下。建议您不要在生产环境中使用它,或者,如果必须,请在从属服务器上发布它。
考虑到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");
这将变得更快,并且不需要任何特殊的东西。
答案 1 :(得分:0)
我知道问题有点老,但基于这个回答:link
在CustomerRepository.cs
using Newtonsoft.Json;
using StackExchange.Redis;
// ...
public class CustomerRepository : ICustomerRepository
{
private readonly IDistributedCache _redis;
private readonly IConfiguration _configuration;
public CustomerRepository(IDistributedCache redis, IConfiguration configuration)
{
_redis = redis;
_configuration = configuration;
}
///<summary>replace `object` with `class name`</summary>
public async Task<object> GetCustomersAsync(string name)
{
ConfigurationOptions options = ConfigurationOptions.Parse(_configuration.GetConnectionString("DefaultConnection"));
ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(options);
IDatabase db = connection.GetDatabase();
EndPoint endPoint = connection.GetEndPoints().First();
var pattern = $"application:customer:{name}:*";
RedisKey[] keys = connection.GetServer(endPoint).Keys(pattern: pattern).ToArray();
var server = connection.GetServer(endPoint);
var result = await _redis.GetStringAsync(key);
return JsonConvert.DeserializeObject<object>(result);
}
}
在appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "localhost:6379,password=yourpassword"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}