客户端用的是ServiceStack.Redis,用了连接池。
public sealed class RedisManager { private static PooledRedisClientManager prcm; static RedisManager() { CreateManager(); timer = new Timer(); } private static void CreateManager() { prcm = new PooledRedisClientManager(RedisConfigHelper.Config.ReadServerList, RedisConfigHelper.Config.ReadServerList, new RedisClientManagerConfig { MaxWritePoolSize = RedisConfigHelper.Config.MaxWritePoolSize, MaxReadPoolSize = RedisConfigHelper.Config.MaxReadPoolSize, AutoStart = true }); } public static IRedisClient GetClient() { if (prcm == null) CreateManager(); IRedisClient client = prcm.GetClient(); return client; } }
调用的时候用RedisManager.GetClient()即可,但有一个问题,如果Redis当机或是网络中断,导致得到的client是不可用的,对这个client做任何操作都会产生异常,能不能有一个心跳的机制?定时发一个心跳到Redis来判断是否正常?如果能,该怎么做?
我是通过这个方法来判断是否连通的
private static bool Ping(RedisClient client)
{
try
{
if (client.Ping())
{
return true;
}
else {
return false;
}
}
catch
{
return false;
}
}
如果连接不同 Ping() 会有一点延迟,好像是内部已经实现了重连的判断,
如果连接通是没有延迟直接过的。
不错,学习一下
我感觉这个ServiceStack.Redis有问题,未知的时候断开,然后不会重练,报异常,
比如,socket未知原因断开,然后ping是通的,所以不会重练,ServiceStack.Redis内部的netstream读取会暴异常!
对于这个问题我恨纠结,不多说,上异常
System.Net.Sockets.SocketException: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.BufferedStream.ReadByte()
at ServiceStack.Redis.RedisNativeClient.ReadLine()
at ServiceStack.Redis.RedisNativeClient.ReadData()
at ServiceStack.Redis.RedisNativeClient.SendExpectData(Byte[][] cmdWithBinaryArgs)
at ServiceStack.Redis.RedisNativeClient.GetBytes(String key)
at ServiceStack.Redis.RedisClient.GetValue(String key)
at ServiceStack.Redis.RedisClient.get_Item(String key)