【问题标题】:Redis Cache Number of connected clients increasingRedis Cache 连接的客户端数量增加
【发布时间】:2019-01-28 07:49:30
【问题描述】:

我正在开发一个微服务架构应用程序,我在其中使用 Redis 缓存来缓存常用信息。问题是连接的客户端数量不断增加,我不知道为什么。

我正在从 ASP.NET Web API 和 Web 作业访问 Redis 缓存。用于连接的 NuGet 包是“StackExchange.Redis”(https://github.com/StackExchange/StackExchange.Redis)。

我在代码中连接Redis的方式如下:

connection = ConnectionMultiplexer.Connect(configurationOptions);
connection.ConnectionFailed += ConnectionFailed;
connection.ConnectionRestored += ConnectionRestored;
connection.InternalError += InternalError;

if (!connection.IsConnected)
{
    //_traceSource.TraceWarning($"Connection to REDIS '{_endpointAddress}' was not established.");
}

database = connection.GetDatabase();

return database;

此外,我还实现了 Dispose() 方法以确保正确断开连接:

public void Dispose()
{
   connection?.Close(true);
}

【问题讨论】:

  • 看起来您的应用创建了新连接,但没有关闭它们
  • 你应该共享同一个静态ConnectionMultiplexer

标签: c# redis stackexchange.redis


【解决方案1】:

像这样实现一个静态 Helper 类。

/// <summary>
/// Helper class for connection with Redis Server.
/// </summary>
public static class Helper
{
    /// <summary>
    /// Configuration option to connect with Redis Database.
    /// </summary>
    private static Lazy<ConfigurationOptions> configOptions = new Lazy<ConfigurationOptions>(() =>
    {
        var configOptions = new ConfigurationOptions();
        configOptions.EndPoints.Add("Your Redis sever name");
        configOptions.AbortOnConnectFail = false;
        configOptions.AllowAdmin = true;
        configOptions.KeepAlive = 4;
        configOptions.Password = "Redis server password";
        return configOptions;
    });

    private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configOptions.Value));

    /// <summary>
    /// Connection property to connect Redis Database.
    /// </summary>
    public static ConnectionMultiplexer Connection
    {
        get
        {
            return lazyConnection.Value;
        }
    }
}

之后在任何需要的地方使用它。

var RedisDatabase = Helper.Connection.GetDatabase(Database Number);

这将自动保持连接。希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我会采取以下 3 个步骤:

    1. 添加调用connection.close()的关闭钩子。

      参考:How to call event before Environment.Exit()?

      但并非总是guaranteed to be called。因此,#2:

    2. 使用客户端超时配置 Redis 以关闭空闲连接 > 某个阈值 https://redis.io/topics/clients

    3. 确保不会不必要地创建重复连接。例如:每次调用 Redis 都会创建一个新连接。 @Keyur Ra​​moliya 的回答似乎解决了这个问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 2012-04-14
      • 2011-09-12
      • 2015-07-09
      相关资源
      最近更新 更多