GithubResolver.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using DNS.Client;
  2. using Microsoft.Extensions.Caching.Memory;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace FastGithub.ReverseProxy
  12. {
  13. /// <summary>
  14. /// github解析器
  15. /// </summary>
  16. sealed class GithubResolver
  17. {
  18. private readonly IMemoryCache memoryCache;
  19. private readonly IOptionsMonitor<FastGithubOptions> options;
  20. private readonly ILogger<GithubResolver> logger;
  21. /// <summary>
  22. /// github解析器
  23. /// </summary>
  24. /// <param name="options"></param>
  25. public GithubResolver(
  26. IMemoryCache memoryCache,
  27. IOptionsMonitor<FastGithubOptions> options,
  28. ILogger<GithubResolver> logger)
  29. {
  30. this.memoryCache = memoryCache;
  31. this.options = options;
  32. this.logger = logger;
  33. }
  34. /// <summary>
  35. /// 解析指定的域名
  36. /// </summary>
  37. /// <param name="domain"></param>
  38. /// <returns></returns>
  39. public async Task<IPAddress> ResolveAsync(string domain, CancellationToken cancellationToken)
  40. {
  41. // 缓存,避免做不必要的并发查询
  42. var key = $"domain:{domain}";
  43. var address = await this.memoryCache.GetOrCreateAsync(key, async e =>
  44. {
  45. e.SetAbsoluteExpiration(TimeSpan.FromMinutes(2d));
  46. var dnsClient = new DnsClient(this.options.CurrentValue.TrustedDns.ToIPEndPoint());
  47. var addresses = await dnsClient.Lookup(domain, DNS.Protocol.RecordType.A, cancellationToken);
  48. return addresses?.FirstOrDefault();
  49. });
  50. if (address == null)
  51. {
  52. var message = $"无法解析{domain}的ip";
  53. this.logger.LogWarning(message);
  54. throw new HttpRequestException(message);
  55. }
  56. this.logger.LogInformation($"[{domain}->{address}]");
  57. return address;
  58. }
  59. }
  60. }