This repository has been archived by the owner on May 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 62
/
RoundRobinServerManager.cs
115 lines (93 loc) · 2.12 KB
/
RoundRobinServerManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace FluentCassandra.Connections
{
public class RoundRobinServerManager : IServerManager
{
private readonly object _lock = new object();
private List<Server> _servers;
private Queue<Server> _serverQueue;
private HashSet<Server> _blackListed;
public RoundRobinServerManager(IConnectionBuilder builder)
{
_servers = new List<Server>(builder.Servers);
_serverQueue = new Queue<Server>(_servers);
_blackListed = new HashSet<Server>();
}
private bool IsBlackListed(Server server)
{
return _blackListed.Contains(server);
}
#region IServerManager Members
public bool HasNext
{
get { lock (_lock) { return (_serverQueue.Count - _blackListed.Count) > 0; } }
}
public Server Next()
{
Server server;
lock (_lock)
{
do
{
server = _serverQueue.Dequeue();
if (IsBlackListed(server))
server = null;
else
_serverQueue.Enqueue(server);
}
while (_serverQueue.Count > 0 && server == null);
}
return server;
}
public void Add(Server server)
{
lock (_lock)
{
_servers.Add(server);
_serverQueue.Enqueue(server);
}
}
public void ErrorOccurred(Server server, Exception exc = null)
{
Debug.WriteLineIf(exc != null, exc, "connection");
BlackList(server);
}
public void BlackList(Server server)
{
Debug.WriteLine(server + " has been blacklisted", "connection");
lock (_lock)
{
_blackListed.Add(server);
}
}
public void Remove(Server server)
{
lock (_lock)
{
_servers.Remove(server);
_serverQueue = new Queue<Server>();
_blackListed.RemoveWhere(x => x == server);
foreach (var s in _servers)
{
if (!_blackListed.Contains(s))
_serverQueue.Enqueue(s);
}
}
}
#endregion
#region IEnumerable<Server> Members
public IEnumerator<Server> GetEnumerator()
{
return _servers.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}