using Common; using Infrastructure; using Nacos.V2; using Nacos.V2.DependencyInjection; using Yarp.ReverseProxy.Configuration; public class RefreshYarp : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { // 例如后台定时任务 / Nacos 监听回调里 var provider = App.ServiceProvider.GetRequiredService(); var clusters = new List(); var routes = new List(); var services = new ServiceCollection(); services.AddNacosV2Naming(x => { InternalApp.Configuration.GetSection("NacosConfig").Bind(x); }); var sp = services.BuildServiceProvider(); var naming = sp.GetRequiredService(); var options = App.OptionsSetting; foreach(var service in options.Services) { string serviceName = service.Name; var list = await naming.GetAllInstances(serviceName, "DEFAULT"); var healthy = list.Where(h => h.Healthy && h.Enabled).ToList(); if (healthy.Count > 0) { var dests = healthy.ToDictionary( k => $"{k.Ip}:{k.Port}", v => new DestinationConfig { Address = $"http://{v.Ip}:{v.Port}" }); Console.WriteLine("serviceHosts---" + Newtonsoft.Json.JsonConvert.SerializeObject(dests)); string ClusterId = serviceName + "-cluster"; string RouteId = serviceName + "-route"; if(!clusters.Any(m => m.ClusterId == ClusterId)) { clusters.Add(new ClusterConfig { ClusterId = ClusterId, Destinations = dests }); } else { RouteId += "-" + routes.Count(m => m.ClusterId == ClusterId); } routes.Add(new RouteConfig { RouteId = RouteId, ClusterId = ClusterId, Match = new RouteMatch { Path = service.Path } }); } } // 一键生效,不需要重启 provider.Update(routes, clusters); } catch(Exception ex) { Utils.WriteLog(ex.ToString(), "实时同步nacos服务数据异常"); } await Task.Delay(10000, stoppingToken); } } }