1 ///
2 /// Called within a lock
3 ///
4 ///
5 private RedisClient GetInActiveWriteClient()
6 {
7 var desiredIndex = WritePoolIndex % writeClients.Length;
8 //this will loop through all hosts in readClients once even though there are 2 for loops
9 //both loops are used to try to get the prefered host according to the round robin algorithm
10 for (int x = 0; x < ReadWriteHosts.Count; x++)
11 {
12 var nextHostIndex = (desiredIndex + x) % ReadWriteHosts.Count;
13 var nextHost = ReadWriteHosts[nextHostIndex];
14 for (var i = nextHostIndex; i < writeClients.Length; i += ReadWriteHosts.Count)
15 {
16 if (writeClients != null && !writeClients.Active && !writeClients.HadExceptions)
17 return writeClients;
18 else if (writeClients == null || writeClients.HadExceptions)
19 {
20 if (writeClients != null)
21 writeClients.DisposeConnection();
22 var client = RedisClientFactory.CreateRedisClient(nextHost.Host, nextHost.Port);
23
24 if (nextHost.RequiresAuth)
25 client.Password = nextHost.Password;
26
27 client.Id = RedisClientCounter++;
28 client.ClientManager = this;
29 client.NamespacePrefix = NamespacePrefix;
30 client.ConnectionFilter = ConnectionFilter;
31
32 writeClients = client;
33
34 return client;
35 }
36 }
37 }
38 return null;
39 } 工作原理
以上代码的原理非常简单,就是轮循不同host下的可用连接,如果相关连接可用测直接返回.如果连接损耗则释放重新创建.