Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Redis StackExchange.Redis ConnectionMultiplexer in ASP.net MVC

I have read that in order to connect to Azure Redis cache is best to follow this practice:

private static ConnectionMultiplexer Connection { get { return LazyConnection.Value; } }

    private static readonly Lazy<ConnectionMultiplexer> LazyConnection =
        new Lazy<ConnectionMultiplexer>(
            () =>
            {
                return
                    ConnectionMultiplexer.Connect(connStinrg);
            });

And according to Azure Redis docs:

The connection to the Azure Redis Cache is managed by the ConnectionMultiplexer class. This class is designed to be shared and reused throughout your client application, and does not need to be created on a per operation basis.

So what is best practice for sharing ConnectionMultiplexer across my ASP.net MVC app ? Should it be called in Global.asax, or should I initialize it once per Controller, or smth. else ?

Also I have service which is tasked to communicate with the app, so if I want to communicate with Redis inside the Service should I send instance of ConnectionMultiplexer to service from Controllers, or should I initialize it in all my services, or ?

As you can see I'm a bit lost here, so please help !

like image 264
hyperN Avatar asked Sep 11 '15 13:09

hyperN


2 Answers

The docs are right in that you should have only one instance of ConnectionMultiplexer and reuse it. Don't create more than one, it is recommended that it will be shared and reused.

Now for the creation part, it shouldn't be in Controller or in Global.asax. Normally you should have your own RedisCacheClient class (maybe implementing some ICache interface) that uses a ConnectionMultiplexer private static instance inside and that's where your creation code should be - exactly as you wrote it in your question. The Lazy part will defer the creation of the ConnectionMultiplexer until the first time it is used.

like image 173
Liviu Costea Avatar answered Oct 29 '22 08:10

Liviu Costea


Dears;

You can reuse StackExchange.Redis ConnectionMultiplexer by using the following code. It can be used in any layer of your code.

public class RedisSharedConnection
{
    private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
    {
        ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString);
        connectionMultiplexer.PreserveAsyncOrder = false;
        return connectionMultiplexer;
    });

    public static ConnectionMultiplexer Connection
    {
        get
        {
            return lazyConnection.Value;
        }
    }
}
like image 43
Muhammad Makhaly Avatar answered Oct 29 '22 09:10

Muhammad Makhaly