Microsoft Distrubted Redis缓存-根据模式获取密钥

时间:2018-10-25 08:53:01

标签: asp.net-core redis .net-core asp.net-core-mvc

我们正在使用.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);

这样我们就可以通过此模式获得以下键:

  • application:customer:1234:Profile
  • 应用程序:客户:1234:订单
  • 应用程序:客户:1234:发票
  • 应用程序:客户:1234:付款

使用任何通配符或没有通配符都无法完成这项工作。没有实现另一个Redis nuget软件包的解决方案吗?

2 个答案:

答案 0 :(得分:2)

IDistributeCache接口不支持此功能。它旨在获取/设置特定键,而不是返回一定范围的键。如果您需要执行此类操作,则需要进入基础存储区,即Redis。好消息是您不需要其他任何东西:支持Redis StackExchange.Redis实现所需的同一IDistributedCache库也提供了可以直接使用的客户端。

特别是在这里的情况下,您需要一些代码,例如:

var server = _redis.GetServer(someServer);
foreach(var key in server.Keys(pattern: cacheKey)) {
    // do something
}

在这里,_redisConnectionMultiplexer的实例。这已被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"
    }
  }
}