ProxyManager.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Threading.Tasks;
  5. using System.Linq;
  6. public class ProxyManager
  7. {
  8. private List<ProxyInfo> proxyPool = new List<ProxyInfo>();
  9. private object lockObj = new object();
  10. private DateTime lastResetTime = DateTime.UtcNow;
  11. private TimeSpan resetInterval = TimeSpan.FromHours(1); // 设置重置间隔为1小时
  12. public ProxyManager(IEnumerable<string> proxyAddresses)
  13. {
  14. foreach (var address in proxyAddresses)
  15. {
  16. proxyPool.Add(new ProxyInfo(new WebProxy(address)));
  17. }
  18. }
  19. public WebProxy GetNextProxy()
  20. {
  21. lock (lockObj)
  22. {
  23. if (DateTime.UtcNow - lastResetTime >= resetInterval) ResetCounters();
  24. var nextProxy = proxyPool.OrderBy(p => p.UsageCount).FirstOrDefault(p => p.IsAvailable);
  25. if (nextProxy != null)
  26. {
  27. nextProxy.UsageCount++;
  28. return nextProxy.Proxy;
  29. }
  30. return null; // 没有可用的代理时返回 null
  31. }
  32. }
  33. private void ResetCounters()
  34. {
  35. foreach (var proxyInfo in proxyPool)
  36. {
  37. proxyInfo.UsageCount = 0;
  38. }
  39. lastResetTime = DateTime.UtcNow;
  40. }
  41. public void ReportProxyResult(WebProxy proxy, bool isSuccess)
  42. {
  43. lock (lockObj)
  44. {
  45. var proxyInfo = proxyPool.Find(p => p.Proxy == proxy);
  46. if (proxyInfo != null)
  47. {
  48. if (isSuccess)
  49. {
  50. proxyInfo.Failures = 0;
  51. proxyInfo.IsAvailable = true;
  52. }
  53. else
  54. {
  55. proxyInfo.Failures++;
  56. proxyInfo.IsAvailable = false;
  57. proxyInfo.LastUnavailable = DateTime.UtcNow;
  58. if (proxyInfo.Failures >= 3)
  59. {
  60. proxyInfo.IsAvailable = false;
  61. SendAlert(proxyInfo);
  62. // 使用异步任务恢复代理可用状态
  63. Task.Run(async () =>
  64. {
  65. await Task.Delay(TimeSpan.FromMinutes(1));
  66. lock (lockObj)
  67. {
  68. // 只有在这段时间内没有再次标记为不可用时才重置代理状态
  69. if (!proxyInfo.IsAvailable)
  70. {
  71. proxyInfo.IsAvailable = true;
  72. }
  73. }
  74. });
  75. }
  76. }
  77. }
  78. }
  79. }
  80. private void SendAlert(ProxyInfo proxyInfo)
  81. {
  82. Console.WriteLine($"Alert: Proxy {proxyInfo.Proxy.Address} is repeatedly failing.");
  83. }
  84. }
  85. public class ProxyInfo
  86. {
  87. public WebProxy Proxy { get; }
  88. public bool IsAvailable { get; set; }
  89. public int UsageCount { get; set; }
  90. public int Failures { get; set; }
  91. public DateTime LastUnavailable { get; set; }
  92. public ProxyInfo(WebProxy proxy)
  93. {
  94. Proxy = proxy;
  95. IsAvailable = true;
  96. UsageCount = 0;
  97. Failures = 0;
  98. LastUnavailable = DateTime.MinValue;
  99. }
  100. }