forked from NetCoreStack/Proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoundRobinManager.cs
More file actions
62 lines (51 loc) · 1.9 KB
/
RoundRobinManager.cs
File metadata and controls
62 lines (51 loc) · 1.9 KB
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
using Microsoft.Extensions.Options;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace NetCoreStack.Proxy
{
public class RoundRobinManager
{
private static readonly object _lockObj = new object();
public readonly ConcurrentDictionary<string, Queue<string>> ProxyRegionDict =
new ConcurrentDictionary<string, Queue<string>>();
protected ProxyOptions Options { get; }
public RoundRobinManager(IOptions<ProxyOptions> options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (options.Value == null || options.Value.RegionKeys == null)
{
throw new ArgumentNullException(nameof(options.Value.RegionKeys));
}
Options = options.Value;
Dictionary<string, string> regionKeys = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> entry in Options.RegionKeys)
{
if (string.IsNullOrEmpty(entry.Value))
continue;
var urls = entry.Value.Split(',').Select(p => p.Trim()).ToList();
ProxyRegionDict.TryAdd(entry.Key, new Queue<string>(urls));
}
}
public UriBuilder RoundRobinUri(string regionKey)
{
UriBuilder uri = null;
Queue<string> queue;
if (!ProxyRegionDict.TryGetValue(regionKey, out queue))
{
throw new ArgumentOutOfRangeException($"Region could not be found! {nameof(RoundRobinManager)}: \"{regionKey}\"");
}
lock (_lockObj)
{
var url = queue.Dequeue();
uri = new UriBuilder(url);
queue.Enqueue(url);
return uri;
}
}
}
}