ProxyNodesCore.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.AspNetCore.Mvc.Controllers;
  3. using Microsoft.AspNetCore.Mvc.Filters;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using dodohold.core;
  9. using Spire.Pdf.Exporting.XPS.Schema;
  10. using System.Xml.Linq;
  11. using System.Net;
  12. using TencentCloud.Mrs.V20200910.Models;
  13. using static molilian.core.TkPoolCore;
  14. namespace molilian.core
  15. {
  16. public partial class ProxyNodesCore
  17. {
  18. private static string _end_point;
  19. static ProxyNodesCore()
  20. {
  21. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  22. }
  23. private static readonly object _lockObj = new();
  24. private static IEnumerable<ProxyNodesDTO> _cached;
  25. public static WebProxy? GetOne(string node)
  26. {
  27. var list = List();
  28. if (!list.Any()) return null;
  29. //var ProxyNodesDTO = list.Where(s => s.name == node).FirstOrDefault();
  30. var ProxyNodesDTO = list.Where(e => SelectEndPointUseProxy(e, node)).OrderBy(l => Guid.NewGuid()).FirstOrDefault();
  31. if (ProxyNodesDTO == null) return null;
  32. return new WebProxy
  33. {
  34. Address = new Uri(ProxyNodesDTO.server),
  35. Credentials = new NetworkCredential(ProxyNodesDTO.username, ProxyNodesDTO.password)
  36. };
  37. }
  38. private static bool SelectEndPointUseProxy(ProxyNodesDTO item, string node)
  39. {
  40. if (!string.IsNullOrEmpty(_end_point) && !string.IsNullOrEmpty(item.end_point))
  41. {
  42. if (item.end_point != _end_point) return false;
  43. }
  44. return item.name == node;
  45. }
  46. public static IEnumerable<ProxyNodesDTO> List(bool force = false)
  47. {
  48. if (!force && _cached != null) return _cached;
  49. string cache_key = $"cache:proxy_nodes";
  50. var list = RedisHelper.Get<IEnumerable<ProxyNodesDTO>>(cache_key);
  51. if (force || list == null)
  52. {
  53. lock (_lockObj)
  54. {
  55. list = new DBContext.Table("proxy_nodes")
  56. .Where("status=@status", new { status = 1 })
  57. .Select<ProxyNodesDTO>();
  58. if (list == null) return default;
  59. RedisHelper.Set(cache_key, list, 30 * 86400);
  60. }
  61. }
  62. _cached = list;
  63. return list;
  64. }
  65. public static void Refresh()
  66. {
  67. _cached = null;
  68. _ = List(true);
  69. }
  70. }
  71. }