场景
Winform/Csharp中使用StackExchange.Redis连接Redis存取数据并序列化对象/反序列化(支持redis key 模糊搜索):
Winform/Csharp中使用StackExchange.Redis连接Redis存取数据并序列化对象/反序列化(支持redis key 模糊搜索)_霸道流氓气质的博客
在上面实现连接Redis并通过连接字符串连接时,如果连接字符串写错或者连不到
Redis时,会直接报错。如何在连接之前先校验下redis的可连通性。
注:
博客:霸道流氓气质的博客C#,架构之路,SpringBoot领域博主
实现
1、原来发起连接的方法
private static ConnectionMultiplexer GetManager(string connectionString = null)
{
connectionString = connectionString ?? RedisConnectionString;
var connect = ConnectionMultiplexer.Connect(connectionString);
//注册如下事件
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
return connect;
}
2、增加一个发起连接的方法,并使用try-catch,如果未报错则认为可连。
public static bool CheckConnectValidity(string connectionString)
{
try {
ConnectionMultiplexer.Connect(connectionString);
return true;
} catch (Exception exception) {
return false;
}
}
新增可连性检测的方法,参数是传递的连接字符串。
在发起连接并实例化RedsiHelper时先进行可行性校验
if (RedisConnectionHelp.CheckConnectValidity(RedisConnectionString))
{
redis = new RedisHelper();
textBox_log.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":连接redis数据库成功!!");
textBox_log.AppendText("\r\n");
return true;
}
else {
return false;
}