| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- 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<InMemoryConfigProvider>();
- var clusters = new List<ClusterConfig>();
- var routes = new List<RouteConfig>();
- var services = new ServiceCollection();
- services.AddNacosV2Naming(x =>
- {
- InternalApp.Configuration.GetSection("NacosConfig").Bind(x);
- });
- var sp = services.BuildServiceProvider();
- var naming = sp.GetRequiredService<INacosNamingService>();
- 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);
- }
- }
- }
|