forked from shiftwinting/FastGithub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GithubContextCollection.cs
74 lines (68 loc) · 2.26 KB
/
GithubContextCollection.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
using System.Collections.Generic;
using System.Linq;
using System.Net;
namespace FastGithub.Scanner
{
sealed class GithubContextCollection
{
private readonly object syncRoot = new();
private readonly HashSet<GithubContext> contextHashSet = new();
private readonly Dictionary<string, IPAddress> domainAdressCache = new();
public void AddOrUpdate(GithubContext context)
{
lock (this.syncRoot)
{
if (this.contextHashSet.TryGetValue(context, out var value))
{
value.Elapsed = context.Elapsed;
value.Available = context.Available;
}
else
{
this.contextHashSet.Add(context);
}
}
}
public GithubContext[] ToArray()
{
lock (this.syncRoot)
{
return this.contextHashSet.ToArray();
}
}
/// <summary>
/// 查找又稳又快的ip
/// </summary>
/// <param name="domain"></param>
/// <returns></returns>
public IPAddress? FindFastAddress(string domain)
{
lock (this.syncRoot)
{
// 如果上一次的ip可以使用,就返回上一次的ip
if (this.domainAdressCache.TryGetValue(domain, out var address))
{
var key = new GithubContext(domain, address);
if (this.contextHashSet.TryGetValue(key, out var context) && context.Available)
{
return address;
}
}
var fastAddress = this.contextHashSet
.Where(item => item.Available && item.Domain == domain)
.OrderBy(item => item.Elapsed)
.Select(item => item.Address)
.FirstOrDefault();
if (fastAddress != null)
{
this.domainAdressCache[domain] = fastAddress;
}
else
{
this.domainAdressCache.Remove(domain);
}
return fastAddress;
}
}
}
}