Ver Fonte

实时获取其他服务地址

lichunlei há 5 meses atrás
pai
commit
ca5dd2581f
3 ficheiros alterados com 59 adições e 0 exclusões
  1. 7 0
      Model/Base/OptionsSetting.cs
  2. 1 0
      Program.cs
  3. 51 0
      Util/RefreshService.cs

+ 7 - 0
Model/Base/OptionsSetting.cs

@@ -27,6 +27,7 @@ namespace Infrastructure.Model
         public List<DbConfigs> DbConfigs { get; set; }
         public DbConfigs CodeGenDbConfig { get; set; }
         public RabbitMqConfigs RabbitMqConfigs { get; set; }
+        public List<ServiceItem> Services { get; set; }
     }
     /// <summary>
     /// 发送邮件数据配置
@@ -143,4 +144,10 @@ namespace Infrastructure.Model
         public string HostName { get; set; }
         public string VirtualHostName { get; set; }
     }
+
+    public class ServiceItem
+    {
+        public string Name { get; set; }
+        public string Path { get; set; }
+    }
 }

+ 1 - 0
Program.cs

@@ -83,6 +83,7 @@ builder.Services.AddMvc(options =>
 
 builder.Services.AddSummerBoot();
 builder.Services.AddSummerBootFeign();
+builder.Services.AddHostedService<RefreshService>();
 
 var app = builder.Build();
 InternalApp.ServiceProvider = app.Services;

+ 51 - 0
Util/RefreshService.cs

@@ -0,0 +1,51 @@
+using Common;
+using Infrastructure;
+using Nacos.V2;
+using Nacos.V2.DependencyInjection;
+
+public class RefreshService : BackgroundService
+{
+    private readonly INacosNamingService _namingService;
+
+    public RefreshService(INacosNamingService namingService)
+    {
+        _namingService = namingService;
+    }
+
+    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+    {
+        while (!stoppingToken.IsCancellationRequested)
+        {
+            try
+            {
+                var options = App.OptionsSetting;
+                foreach(var service in options.Services)
+                {
+                    string serviceName = service.Name;
+                    var list = await _namingService.GetAllInstances(serviceName, "DEFAULT");
+                    var healthy = list.Where(h => h.Healthy && h.Enabled).ToList();
+
+                    if (healthy.Count > 0)
+                    {
+                        foreach(var sub in healthy)
+                        {
+                            if(!Utils.FeignUrl.ContainsKey(serviceName))
+                            {
+                                Utils.FeignUrl.Add(serviceName, "http://" + sub.Ip + ":" + sub.Port);
+                            }
+                            else
+                            {
+                                Utils.FeignUrl[serviceName] = "http://" + sub.Ip + ":" + sub.Port;
+                            }
+                        }
+                    }
+                }
+            }
+            catch(Exception ex)
+            {
+                Utils.WriteLog(ex.ToString(), "实时同步nacos服务数据异常");
+            }
+            await Task.Delay(10000, stoppingToken);
+        }
+    }
+}