ASP.net MVC中的Azure Redis StackExchange.Redis ConnectionMultiplexer

时间:2015-09-11 13:58:34

标签: c# asp.net-mvc redis stackexchange.redis azure-redis-cache

我已经读过,为了连接到Azure Redis缓存,最好遵循以下做法:

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

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

根据Azure Redis文档:

  

Azure Redis缓存的连接由ConnectionMultiplexer类管理。此类旨在在整个客户端应用程序中共享和重用,而不需要在每个操作的基础上创建。

那么在我的ASP.net MVC应用程序中共享ConnectionMultiplexer的最佳做法是什么? 它应该在Global.asax中调用,还是应该每个Controller初始化一次,或者smth。别的?

此外,我还有一项服务,其任务是与应用程序进行通信,因此如果我想在服务中与Redis通信,我应该将ConnectionMultiplexer的实例发送到控制器的服务,还是应该在我的所有服务中初始化它,或者?

你可以看到我在这里有点迷失,所以请帮忙!

2 个答案:

答案 0 :(得分:6)

文档是正确的,你应该只有一个ConnectionMultiplexer实例并重用它。不要创建多个,建议它是shared and reused

现在对于创建部分,它不应该在Controller或Global.asax中。通常,您应该拥有自己的RedisCacheClient类(可能实现一些ICache接口),该类使用内部的ConnectionMultiplexer私有静态实例,这就是您的创建代码所在的位置 - 正如您在问题中所写的那样。 Lazy部分将推迟ConnectionMultiplexer的创建,直到第一次使用它为止。

答案 1 :(得分:0)

逗人;

您可以使用以下代码重用StackExchange.Redis ConnectionMultiplexer。它可以在代码的任何层中使用。

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