我正在.net核心2.0中构建web apis,并将其部署在kubernetes.I上。我想使用IDistributedCache (带有redis)和前哨和主/从配置。我找不到任何关于这方面的文档。它如何处理主/从场景(故障切换情况)?
发布于 2018-04-20 07:40:11
看一下源代码就会知道你需要知道的一切: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
https://stackoverflow.com/questions/49403973
复制相似问题