【问题标题】:C# Asp.Net Core Use Redis for IDistributedMemoryCache and DataProtectionC# Asp.Net Core 使用 Redis 进行 ADDDistributedMemoryCache 和数据保护
【发布时间】:2021-12-21 05:35:33
【问题描述】:

正如标题所暗示的,我应该同时使用 Redis 作为 DistributedCache 并存储 DataProtection 的密钥,问题是我不知道两次注册 Redis 实例是否正确,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    //......

    // First Instance of Redis
    serviceCollection.AddStackExchangeRedisCache(options =>
    {
        options.ConfigurationOptions = new ConfigurationOptions();
        options.ConfigurationOptions.EndPoints.Add("127.0.0.1", 6379);
        options.ConfigurationOptions.Password = "*********";
        options.ConfigurationOptions.ConnectRetry = 5;
    });

    // Second Instance of Redis
    var redis = ConnectionMultiplexer.Connect("127.0.0.1:6379");
    serviceCollection.AddDataProtection()
        .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");

    //......
}

或者可以共享已经在第一种方法中注册的同一个实例?
万一有可能来做什么? 谢谢

【问题讨论】:

    标签: c# asp.net-core redis


    【解决方案1】:

    在 .NET 6 中,微软在配置 redis 时添加了新选项以允许 get 或 set delegate 来创建 ConnectionMultiplexer,下面是简单的示例

    ConnectionMultiplexer cm = ConnectionMultiplexer.Connect("server1:6729");
    services.AddSingleton<IConnectionMultiplexer>(cm);
    
    services.AddStackExchangeRedisCache(options =>
            {
                options.ConnectionMultiplexerFactory = () =>
                {
                    var serviceProvider = services.BuildServiceProvider();
                    IConnectionMultiplexer connection = serviceProvider.GetService<IConnectionMultiplexer>();
                    return Task.FromResult(connection);
                };
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2022-01-24
      • 2021-08-22
      相关资源
      最近更新 更多