继续改造代码:
IServiceHelper增加一个获取服务列表的接口方法:
ServiceHelper实现接口:
public class ServiceHelper : IServiceHelper { private readonly IConfiguration _configuration; private readonly ConsulClient _consulClient; private ConcurrentBag<string> _orderServiceUrls; private ConcurrentBag<string> _productServiceUrls; public ServiceHelper(IConfiguration configuration) { _configuration = configuration; _consulClient = new ConsulClient(c => { //consul地址 c.Address = new Uri(_configuration["ConsulSetting:ConsulAddress"]); }); } public async Task<string> GetOrder() { if (_productServiceUrls == null) return await Task.FromResult("【订单服务】正在初始化服务列表..."); //每次随机访问一个服务实例 var Client = new RestClient(_orderServiceUrls.ElementAt(new Random().Next(0, _orderServiceUrls.Count()))); var request = new RestRequest("/orders", Method.GET); var response = await Client.ExecuteAsync(request); return response.Content; } public async Task<string> GetProduct() { if(_productServiceUrls == null) return await Task.FromResult("【产品服务】正在初始化服务列表..."); //每次随机访问一个服务实例 var Client = new RestClient(_productServiceUrls.ElementAt(new Random().Next(0, _productServiceUrls.Count()))); var request = new RestRequest("/products", Method.GET); var response = await Client.ExecuteAsync(request); return response.Content; } public void GetServices() { var serviceNames = new string[] { "OrderService", "ProductService" }; Array.ForEach(serviceNames, p => { Task.Run(() => { //WaitTime默认为5分钟 var queryOptions = new QueryOptions { WaitTime = TimeSpan.FromMinutes(10) }; while (true) { GetServices(queryOptions, p); } }); }); } private void GetServices(QueryOptions queryOptions, string serviceName) { var res = _consulClient.Health.Service(serviceName, null, true, queryOptions).Result; //控制台打印一下获取服务列表的响应时间等信息 Console.WriteLine($"{DateTime.Now}获取{serviceName}:queryOptions.WaitIndex:{queryOptions.WaitIndex} LastIndex:{res.LastIndex}"); //版本号不一致 说明服务列表发生了变化 if (queryOptions.WaitIndex != res.LastIndex) { queryOptions.WaitIndex = res.LastIndex; //服务地址列表 var serviceUrls = res.Response.Select(p => $"http://{p.Service.Address + ":" + p.Service.Port}").ToArray(); if (serviceName == "OrderService") _orderServiceUrls = new ConcurrentBag<string>(serviceUrls); else if (serviceName == "ProductService") _productServiceUrls = new ConcurrentBag<string>(serviceUrls); } } }Startup的Configure方法中调用一下获取服务列表:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceHelper serviceHelper) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); //程序启动时 获取服务列表 serviceHelper.GetServices(); }代码完成,运行测试:
现在不用每次先请求服务列表了,是不是流畅多了?
看一下控制台打印:
这时候如果服务列表没有发生变化的话,获取服务列表的请求会一直阻塞到我们设置的10分钟。
随便停止2个服务:
这时候可以看到,数据被立马返回了。