RefreshYarp.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using Common;
  2. using Infrastructure;
  3. using Nacos.V2;
  4. using Nacos.V2.DependencyInjection;
  5. using Yarp.ReverseProxy.Configuration;
  6. public class RefreshYarp : BackgroundService
  7. {
  8. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  9. {
  10. while (!stoppingToken.IsCancellationRequested)
  11. {
  12. try
  13. {
  14. // 例如后台定时任务 / Nacos 监听回调里
  15. var provider = App.ServiceProvider.GetRequiredService<InMemoryConfigProvider>();
  16. var clusters = new List<ClusterConfig>();
  17. var routes = new List<RouteConfig>();
  18. var naming = App.ServiceProvider.GetRequiredService<INacosNamingService>();
  19. var options = App.OptionsSetting;
  20. foreach(var service in options.Services)
  21. {
  22. string serviceName = service.Name;
  23. var list = await naming.GetAllInstances(serviceName, "DEFAULT");
  24. var healthy = list.Where(h => h.Healthy && h.Enabled).ToList();
  25. if (healthy.Count > 0)
  26. {
  27. var dests = healthy.ToDictionary(
  28. k => $"{k.Ip}:{k.Port}",
  29. v => new DestinationConfig { Address = $"http://{v.Ip}:{v.Port}" });
  30. Console.WriteLine("serviceHosts---" + Newtonsoft.Json.JsonConvert.SerializeObject(dests));
  31. string ClusterId = serviceName + "-cluster";
  32. string RouteId = serviceName + "-route";
  33. if(!clusters.Any(m => m.ClusterId == ClusterId))
  34. {
  35. clusters.Add(new ClusterConfig
  36. {
  37. ClusterId = ClusterId,
  38. Destinations = dests
  39. });
  40. }
  41. else
  42. {
  43. RouteId += "-" + routes.Count(m => m.ClusterId == ClusterId);
  44. }
  45. routes.Add(new RouteConfig
  46. {
  47. RouteId = RouteId,
  48. ClusterId = ClusterId,
  49. Match = new RouteMatch { Path = service.Path }
  50. });
  51. }
  52. }
  53. // 一键生效,不需要重启
  54. provider.Update(routes, clusters);
  55. }
  56. catch(Exception ex)
  57. {
  58. Utils.WriteLog(ex.ToString(), "实时同步nacos服务数据异常");
  59. }
  60. await Task.Delay(60000, stoppingToken);
  61. }
  62. }
  63. }