///
/// Called within a lock
///
///
private RedisClient GetInActiveWriteClient()
{
var desiredIndex = WritePoolIndex % writeClients.Length;
//this will loop through all hosts in readClients once even though there are 2 for loops
//both loops are used to try to get the prefered host according to the round robin algorithm
for (int x = 0; x < ReadWriteHosts.Count; x++)
{
var nextHostIndex = (desiredIndex + x) % ReadWriteHosts.Count;
var nextHost = ReadWriteHosts[nextHostIndex];
if (nextHost.Detect())
{
RedisClient client = nextHost.Pop();
if (client != null)
{
if (nextHost.RequiresAuth)
client.Password = nextHost.Password;
client.Id = RedisClientCounter++;
client.ClientManager = this;
client.NamespacePrefix = NamespacePrefix;
client.ConnectionFilter = ConnectionFilter;
return client;
}
}
//for (var i = nextHostIndex; i < writeClients.Length; i += ReadWriteHosts.Count)
//{
// if (writeClients != null && !writeClients.Active && !writeClients.HadExceptions)
// return writeClients;
// else if (writeClients == null || writeClients.HadExceptions)
// {
// if (writeClients != null)
// writeClients.DisposeConnection();
// var client = RedisClientFactory.CreateRedisClient(nextHost.Host, nextHost.Port);
// if (nextHost.RequiresAuth)
// client.Password = nextHost.Password;
// client.Id = RedisClientCounter++;
// client.ClientManager = this;
// client.NamespacePrefix = NamespacePrefix;
// client.ConnectionFilter = ConnectionFilter;
// writeClients = client;
// return client;
// }
//}
}
return null;
}
把代码改成直接检测当明的Host是否有效,如果是则获取连接并返回,这里只修改的writerclient,类里面还有readclient的方法也相对应用进行修改. GetClient方法代码
///
/// Returns a Read/Write client (The default) using the hosts defined in ReadWriteHosts
///
///
public IRedisClient GetClient()
{
lock (writeClients)
{
AssertValidReadWritePool();
RedisClient inActiveClient;
inActiveClient = GetInActiveWriteClient();
if(inActiveClient == null)
throw new TimeoutException(PoolTimeoutError);
//while ((inActiveClient = GetInActiveWriteClient()) == null)
//{
// if (PoolTimeOut.HasValue)
// {
// // wait for a connection, cry out if made to wait too long
// if (!Monitor.Wait(writeClients, PoolTimeOut.Value))
// throw new TimeoutException(PoolTimeoutError);
// }
// else
// Monitor.Wait(writeClients);
//}