caching - 为什么与 Azure Redis 缓存的连接如此高?

标签 caching azure redis-cache azure-redis-cache

我在单台计算机查询缓存的高负载场景中使用 Azure Redis 缓存。这台机器大约每秒获取和设置大约 20 个项目。白天此值增加,夜间此值减少。

到目前为止,一切进展顺利。今天我意识到“连接的客户端”的指标非常高,尽管我只有 1 个客户端不断获取和设置项目。这是我所说的指标的屏幕截图: Redis Cache Connected Clients

我的代码如下所示:

public class RedisCache<TValue> : ICache<TValue>
{
    private IDatabase cache;
    private ConnectionMultiplexer connectionMultiplexer;

    public RedisCache()
    {
        ConfigurationOptions config = new ConfigurationOptions();
        config.EndPoints.Add(GlobalConfig.Instance.GetConfig("RedisCacheUrl"));
        config.Password = GlobalConfig.Instance.GetConfig("RedisCachePassword");
        config.ConnectRetry = int.MaxValue; // retry connection if broken
        config.KeepAlive = 60; // keep connection alive (ping every minute)
        config.Ssl = true;
        config.SyncTimeout = 8000; // 8 seconds timeout for each get/set/remove operation
        config.ConnectTimeout = 20000; // 20 seconds to connect to the cache

        connectionMultiplexer = ConnectionMultiplexer.Connect(config);
        cache = connectionMultiplexer.GetDatabase();
    }

    public virtual bool Add(string key, TValue item)
    {
        return cache.StringSet(key, RawSerializationHelper.Serialize(item));
    }

我没有创建该类的多个实例,所以这不是问题。也许我误解了连接指标,它们真正的意思是我访问缓存的次数,但是,在我看来,它并没有真正意义。有什么想法,或者有类似问题的人吗?

最佳答案

StackExchange.Redis 存在竞争条件,在某些情况下可能会导致连接泄漏。此问题已在版本 1.0.333 或更高版本中修复。

如果您想确认这是您遇到的问题,请获取客户端应用程序的故障转储并在调试器中查看堆上的对象。查找大量 StackExchange.Redis.ServerEndPoint 对象。

此外,一些用户的代码中存在错误,导致连接对象泄漏。这通常是因为他们的代码在看到失败或断开连接状态时尝试重新创建 ConnectionMultiplexer 对象。实际上不需要重新创建 ConnectionMultiplexer,因为它内部具有根据需要重新创建连接的逻辑。只需确保在连接字符串中将 abortConnect 设置为 false。

如果您决定重新创建连接对象,请确保在释放对旧对象的所有引用之前处置旧对象。

以下是我们推荐的模式:


        private static Lazy lazyConnection = new Lazy(() => {
            return ConnectionMultiplexer.Connect("contoso5.redis.cache.windows.net,abortConnect=false,ssl=true,password=...");
        });

        public static ConnectionMultiplexer Connection {
            get {
                return lazyConnection.Value;
            }
        }

关于caching - 为什么与 Azure Redis 缓存的连接如此高?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26033488/

相关文章:

javascript - 如何将 JSON 导入到 Cosmos DB

azure - lex 中单个 lambda 函数的多个返回语句

Azure逻辑应用程序中的Azure Function Produce 404

redis - 获取 Redis 哈希中的字段类型

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

python - 无法在 python 应用程序的 app.yaml 中设置缓存过期

Redis 作为自填充缓存

spring - 如何在 Spring Boot 应用程序的 Redis 缓存管理器中设置不同缓存的最大条目数?

PHP 性能(操作码缓存/函数波动)

python缓存库