c# - Azure Redis 缓存 - ConnectionMultiplexer 对象池

标签 c# caching azure stackexchange.redis azure-redis-cache

我们在应用程序中使用 C1 Azure Redis 缓存。最近,我们在 GET 操作上遇到了大量超时。

According to this article ,可能的解决方案之一是实现 ConnectionMultiplexer 对象池。

Another possible solution is to use a pool of ConnectionMultiplexer objects in your client, and choose the “least loaded” ConnectionMultiplexer when sending a new request. This should prevent a single timeout from causing other requests to also timeout.

使用 C# 实现 ConnectionMultiplexer 对象池会是什么样子?

编辑:

Related question that I asked recently.

最佳答案

您还可以使用 StackExchange.Redis.Extensions 以更简单的方式完成此操作

示例代码:

    using StackExchange.Redis;
    using StackExchange.Redis.Extensions.Core.Abstractions;
    using StackExchange.Redis.Extensions.Core.Configuration;
    using System;
    using System.Collections.Concurrent;
    using System.Linq;

    namespace Pool.Redis
    {
    /// <summary>
    /// Provides redis pool
    /// </summary>
    public class RedisConnectionPool : IRedisCacheConnectionPoolManager
    {
        private static ConcurrentBag<Lazy<ConnectionMultiplexer>> connections;
        private readonly RedisConfiguration redisConfiguration;

        public RedisConnectionPool(RedisConfiguration redisConfiguration)
        {
            this.redisConfiguration = redisConfiguration;
            Initialize();
        }

        public IConnectionMultiplexer GetConnection()
        {
            Lazy<ConnectionMultiplexer> response;
            var loadedLazys = connections.Where(lazy => lazy.IsValueCreated);

            if (loadedLazys.Count() == connections.Count)
            {
                response = connections.OrderBy(x => x.Value.GetCounters().TotalOutstanding).First();
            }
            else
            {
                response = connections.First(lazy => !lazy.IsValueCreated);
            }

            return response.Value;
        }

        private void Initialize()
        {
            connections = new ConcurrentBag<Lazy<ConnectionMultiplexer>>();

            for (int i = 0; i < redisConfiguration.PoolSize; i++)
            {
                connections.Add(new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(redisConfiguration.ConfigurationOptions)));
            }
        }

        public void Dispose()
        {
            var activeConnections = connections.Where(lazy => lazy.IsValueCreated).ToList();
            activeConnections.ForEach(connection => connection.Value.Dispose());
            Initialize();
        }
    }
}

其中RedisConfiguration是这样的:

            return new RedisConfiguration()
        {
            AbortOnConnectFail = true,
            Hosts = new RedisHost[] {
                                      new RedisHost() 
                                      {
                                          Host = ConfigurationManager.AppSettings["RedisCacheAddress"].ToString(),
                                          Port = 6380
                                      },
                                    },
            ConnectTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["RedisTimeout"].ToString()),
            Database = 0,
            Ssl = true,
            Password = ConfigurationManager.AppSettings["RedisCachePassword"].ToString(),
            ServerEnumerationStrategy = new ServerEnumerationStrategy()
            {
                Mode = ServerEnumerationStrategy.ModeOptions.All,
                TargetRole = ServerEnumerationStrategy.TargetRoleOptions.Any,
                UnreachableServerAction = ServerEnumerationStrategy.UnreachableServerActionOptions.Throw
            },
            PoolSize = 50
        };

关于c# - Azure Redis 缓存 - ConnectionMultiplexer 对象池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29603890/

相关文章:

c# - OrderBy的效率和延迟执行

c# - 从 IWpfTextView 获取非 cs 文件的文档路径

c# - 在 C# 中调整图像宽度,但不调整高度

c - 为什么 _mm_stream_ps 会产生 L1/LL 缓存未命中?

c# - 使 ASP.NET 中的缓存对象无效

azure - 验证 Azure 广告访问 token 时签名无效

azure - 在 Web 事件的 header 部分使用 Azure Key Vault key

azure - 从触发 blob 触发器的文件中获取元数据 Azure 函数

c# - 从一个保存文件反序列化多个不相关的 ScriptableObjects

PHP 和 mysql 缓存