Azure Redis StackExchange.Redis ConnectionMultiplexer in ASP.net MVC

落花浮王杯 提交于 2019-12-05 04:51:30
Liviu Costea

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.

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;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!