.net core IDistributedCache redis sentinel支持主/从

时间:2018-03-21 10:33:57

标签: c# redis .net-core

我正在.net core 2.0中构建web apis并在kubernetes上部署它。我想使用带有sentinel和master / slave配置的IDistributedCache(带有redis)。我找不到任何相关的文件。它如何处理主/从场景(故障转移案例)?

1 个答案:

答案 0 :(得分:1)

查看源代码应该告诉您需要知道的一切: https://github.com/aspnet/Caching/blob/dev/src/Microsoft.Extensions.Caching.Redis/RedisCache.cs

如果您正在使用nuget扩展,则IDistributedCache实例应为RedisCache类型。你应该能够施展它:

    public RedisWrapperClassConstructor(IDistributedCache c)
    {
        cche = c as RedisCache;
        //since pub/sub is only supported by Redis, we need to force the issue
        if (cche == null) throw new InvalidCastException("distributed cache must be of type RedisCache");
        EnsureTheConnectionMultiplexerIsSet();
    }

有一个活动请求让扩展将多路复用器公开为依赖注入服务: https://github.com/aspnet/Caching/issues/343

现在你必须使用丑陋的反思:

    private void EnsureTheConnectionMultiplexerIsSet()
    {
        if (_connection != null) return;
        cche.Get("startup"); //populate the connection with a dummy request
        var _connectionMultiplexorFieldInfo = typeof(RedisCache).GetField(nameof(_connection), BindingFlags.NonPublic | BindingFlags.Instance);
        var vl = _connectionMultiplexorFieldInfo.GetValue(cche);
        if (vl != null)
        {
            _connection = (ConnectionMultiplexer)vl;
            if (_connection == null) throw new InvalidCastException("Could not cast the ConnectionMultiplexer");
        }
        if (_connection == null) throw new InvalidCastException("Could not access the ConnectionMultiplexer");
    }

最重要的部分是例外。如果您更新nuget包并且基础类更改了它的字段名称,那么您将要抛出该异常。多路复用器应该在应用程序中共享,因此这是一个非常罕见的例子,您可以证明某些反射。

编辑:我忘了提到如何做哨兵的事情: https://github.com/StackExchange/StackExchange.Redis/pull/406