我在StackExhange.Redis中有一个关于redis sentinel的问题。
Redis版本:3.0.504
StackExchange.Redis版本:1.2.1
我已经在我的电脑(Windows 7)中配置了redis sentinel,如果我关闭了master,
奴隶之一将升级为主人,一切运作良好。但我不知道如何在客户端代码中做到这一点,
我的代码如下:
public class RedisConnectiontHelper
{
private static readonly Lazy<ConnectionMultiplexer> LazyConnection;
static RedisConnectiontHelper()
{
ConfigurationOptions config = new ConfigurationOptions
{
EndPoints =
{
{"127.0.0.1",6379}, // master
{"127.0.0.1",6380}, // slave
{"127.0.0.1",6381} // slave
},
ConnectRetry = 15000,
ConnectTimeout = 15000,
SyncTimeout = 15000
};
LazyConnection = new Lazy<ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(config));
}
public static ConnectionMultiplexer Connection
{
get { return LazyConnection.Value; }
}
}
public class RedisCacheManager
{
public readonly IDatabase RedisDatabase = RedisConnectiontHelper.Connection.GetDatabase();
private static readonly Lazy<RedisCacheManager> CacheManager = new Lazy<RedisCacheManager>(() => new RedisCacheManager());
static RedisCacheManager() { }
public static RedisCacheManager RedisCacheManagerInstance
{
get { return CacheManager.Value; }
}
protected byte[] Serialize(object item)
{
var jsonString = JsonConvert.SerializeObject(item);
return Encoding.UTF8.GetBytes(jsonString);
}
protected T Deserialize<T>(byte[] serializedObject)
{
if (serializedObject == null)
return default(T);
var jsonString = Encoding.UTF8.GetString(serializedObject);
return JsonConvert.DeserializeObject<T>(jsonString);
}
public virtual void Set(string key, object data, int cacheTime)
{
if (data == null)
return;
var entryBytes = Serialize(data);
var expiresIn = TimeSpan.FromMinutes(cacheTime);
RedisDatabase.StringSet(key, entryBytes, expiresIn);
}
}
测试代码:
var redisCacheManager = RedisCacheManager.RedisCacheManagerInstance;
for (int i = 0; i < 50000; i++)
{
string key = "test-" + i;
var model = new RedisSampleModel
{
Key = key,
Name = Guid.NewGuid().ToString()
};
redisCacheManager.Set(key, JsonConvert.SerializeObject(model), 60);
}
在程序仍在执行时,我关闭主服务器,然后在方法“RedisDatabase.StringSet(key,entryBytes,expiresIn);”中抛出错误“远程主机强制关闭连接”;
那我该如何解决这个问题?
有没有办法完成slave自动升级到master并且没有使用StackExchange.Redis的错误?