接上文,服务端部署完成之后,同样我们也需要修改一下客户端代码
在客户端代码中使用Nuget安装consul包
?修改配置文件,我们首先需要把consul的请求地址配置在配置文件中
修改control方法
using Consul;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
namespace ForumClient.Controllers
{
[ApiController]
[Route("api/[controller]/[action]")]
public class ClientController:ControllerBase
{
private readonly ILogger<ClientController> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
public ClientController(IHttpClientFactory httpClientFactory, ILogger<ClientController> logger, IConfiguration configuration)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_configuration = configuration;
}
[HttpGet]
public async Task<string> GetProduct()
{
var client = _httpClientFactory.CreateClient("local"); //
//string[] arr_product_url = { "http://localhost:8050/product", "http://localhost:8051/product", "http://localhost:8052/product" } ;
var consulClient = new ConsulClient(c =>
{
//consul地址
c.Address = new Uri(_configuration["ConsulSetting:ConsulAddress"]);
});
var services = consulClient.Health.Service("ProductService", null, true, null).Result.Response;//健康的服务
string[] serviceUrls = services.Select(p => $"http://{p.Service.Address + ":" + p.Service.Port}").ToArray();//订单服务地址列表
if (!serviceUrls.Any())
{
return await Task.FromResult("【产品服务】服务列表为空");
}
//每次随机访问一个服务实例
var product_result = await client.GetStringAsync(serviceUrls[new Random().Next(0, serviceUrls.Length)]);
return $"产品服务:{product_result}";
}
[HttpGet]
public async Task<string> GetOrder()
{
var client = _httpClientFactory.CreateClient("local"); //
//string[] arr_order_url = { "http://localhost:8060/order", "http://localhost:8061/order", "http://localhost:8062/order" };
var consulClient = new ConsulClient(c =>
{
//consul地址
c.Address = new Uri(_configuration["ConsulSetting:ConsulAddress"]);
});
var services = consulClient.Health.Service("OrderService", null, true, null).Result.Response;//健康的服务
string[] serviceUrls = services.Select(p => $"http://{p.Service.Address + ":" + p.Service.Port}").ToArray();//订单服务地址列表
if (!serviceUrls.Any())
{
return await Task.FromResult("【订单服务】服务列表为空");
}
var order_result = await client.GetStringAsync(serviceUrls[new Random().Next(0, serviceUrls.Length)]);
return $"订单服务:{order_result}";
}
}
}
?OK,通过如下修改,我们发现,我们不需要再在代码中配置请求地址,请求地址可以从consul服务中获取。
ok,我们随便停止两个服务
[root@iZ2ze6on3jy8afby5yaj0bZ order_api]# docker stop orderapi1
orderapi1
[root@iZ2ze6on3jy8afby5yaj0bZ order_api]# docker stop productapi1
productapi1
这时候停止的服务地址就获取不到了,客户端依然正常运行。
这时候解决了服务的发现,新的问题又来了...
那么怎么保证不要每次请求都去Consul获取地址,同时又要拿到可用的地址列表呢?
Consul提供的解决方案:——Blocking Queries (阻塞的请求)
这是什么意思呢,简单来说就是当客户端请求Consul获取地址列表时,需要携带一个版本号信息,Consul会比较这个客户端版本号是否和Consul服务端的版本号一致,如果一致,则Consul会阻塞这个请求,直到Consul中的服务列表发生变化,或者到达阻塞时间上限;如果版本号不一致,则立即返回。这个阻塞时间默认是5分钟,支持自定义。
那么我们另外启动一个线程去干这件事情,就不会影响每次的用户请求了。这样既保证了客户端服务列表的准确性,又节约了客户端请求服务列表的次数。
我们需要继续修改客户端代码。
我们只在构造函数中获取一次服务列表,代码改造结果如下:
using System.Net.Http;
namespace ForumClient.Controllers
{
[ApiController]
[Route("api/[controller]/[action]")]
public class ClientController : ControllerBase
{
private readonly ILogger<ClientController> _logger;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _configuration;
private ConcurrentBag<string> _orderServiceUrls;
private ConcurrentBag<string> _productServiceUrls;
private readonly ConsulClient _consulClient;
public ClientController(IHttpClientFactory httpClientFactory, ILogger<ClientController> logger, IConfiguration configuration)
{
_httpClientFactory = httpClientFactory;
_logger = logger;
_configuration = configuration;
_consulClient = new ConsulClient(c =>
{
//consul地址
c.Address = new Uri(_configuration["ConsulSetting:ConsulAddress"]);
});
GetServices();
}
[HttpGet]
public async Task<string> GetProduct()
{
if (_productServiceUrls == null)
return await Task.FromResult("【产品服务】正在初始化服务列表...");
var client = _httpClientFactory.CreateClient("local"); //
//每次随机访问一个服务实例
var product_result = await client.GetStringAsync(_productServiceUrls.ElementAt(new Random().Next(0, _productServiceUrls.Count())));
return $"产品服务:{product_result}";
}
[HttpGet]
public async Task<string> GetOrder()
{
if (_orderServiceUrls == null)
return await Task.FromResult("【订单服务】正在初始化服务列表...");
var client = _httpClientFactory.CreateClient("local"); //
//每次随机访问一个服务实例
var order_result = await client.GetStringAsync(_orderServiceUrls.ElementAt(new Random().Next(0, _productServiceUrls.Count())));
return $"订单服务:{order_result}";
}
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);
}
}
}
}
现在不用每次调用Api接口的时候都先去请求服务列表了,是不是流畅多了?
这时候如果服务列表没有发生变化的话,获取服务列表的请求会一直阻塞到我们设置的10分钟。
随便停止2个服务:
[root@iZ2ze6on3jy8afby5yaj0bZ order_api]# docker stop orderapi1
orderapi2
[root@iZ2ze6on3jy8afby5yaj0bZ order_api]# docker stop productapi1
productapi2
继续访问客户端网站,同样流畅。
(gif图传的有点问题。。。)
至此,我们就通过Consul完成了服务的注册与发现。
接下来又引发新的思考。。。