3

Azure Portal - Redis Cache - Max Connected Clients

I am developing a microservice architecture application where I am using a Redis Cache to cache frequently used information. The issue is that the number of connected clients is constantly increasing and I don't know why.

I am accessing the Redis Cache from an ASP.NET Web API and a Web Job. The NuGet package used for connection is "StackExchange.Redis" (https://github.com/StackExchange/StackExchange.Redis).

The way I am connecting to Redis in code is as follows:

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;

In addition, I have implemented the Dispose() method to make sure that connections are disconnected properly:

public void Dispose()
{
   connection?.Close(true);
}
Thomas Hahn
  • 171
  • 1
  • 2
  • 12

2 Answers2

2

Implement a static Helper class like this.

/// <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;
        }
    }
}

After that use it like this wherever you need it.

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

This will maintain the connections automatically. Hope this will help.

Keyur Ramoliya
  • 1,900
  • 2
  • 16
  • 17
0

I'd take the following 3 steps :

  1. Add shutdown hook which calls connection.close().

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

    But it's not guaranteed to be called always. Hence, #2:

  2. Configure Redis with client timeout to close connections idle > some threshold https://redis.io/topics/clients

  3. Ensure duplicate connections aren't created unnecessarily. Ex: a new connection is created per call to Redis. @Keyur Ramoliya 's answer seems to address this.

rainhacker
  • 592
  • 2
  • 13