Redis缓存连接的客户端数在增加

时间:2019-01-28 07:49:30

标签: c# redis stackexchange.redis

Azure Portal - Redis Cache - Max Connected Clients

我正在开发一个微服务架构应用程序,其中使用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);
}

2 个答案:

答案 0 :(得分: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);

这将自动维护连接。希望这会有所帮助。

答案 1 :(得分:0)

我将执行以下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的答案似乎解决了这个问题。