RefreshService.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using Common;
  2. using Infrastructure;
  3. using Nacos.V2;
  4. using Nacos.V2.DependencyInjection;
  5. public class RefreshService : BackgroundService
  6. {
  7. private readonly INacosNamingService _namingService;
  8. public RefreshService(INacosNamingService namingService)
  9. {
  10. _namingService = namingService;
  11. }
  12. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  13. {
  14. while (!stoppingToken.IsCancellationRequested)
  15. {
  16. try
  17. {
  18. var options = App.OptionsSetting;
  19. foreach(var service in options.Services)
  20. {
  21. string serviceName = service.Name;
  22. var list = await _namingService.GetAllInstances(serviceName, "DEFAULT_GROUP");
  23. var healthy = list.Where(h => h.Healthy && h.Enabled).ToList();
  24. if (healthy.Count > 0)
  25. {
  26. foreach(var sub in healthy)
  27. {
  28. if(!Utils.FeignUrl.ContainsKey(serviceName))
  29. {
  30. Utils.FeignUrl.Add(serviceName, "http://" + sub.Ip + ":" + sub.Port);
  31. }
  32. else
  33. {
  34. Utils.FeignUrl[serviceName] = "http://" + sub.Ip + ":" + sub.Port;
  35. }
  36. }
  37. }
  38. }
  39. }
  40. catch(Exception ex)
  41. {
  42. Utils.WriteLog(ex.ToString(), "实时同步nacos服务数据异常");
  43. }
  44. await Task.Delay(10000, stoppingToken);
  45. }
  46. }
  47. }