環境 .NET5,Consul_v1.10.2

一、簡介

在微服務中利用Consul可以實現服務的註冊,服務發現,治理,健康檢查等。

Web調站點需要呼叫多個服務,如果沒有Consul,可能就是Web中存了全部服務的ip地址,如果其中一個服務更換了地址,web也要跟著修改配置,所以加入了Consul,web直接通過Consul就能一直取到各個服務的最新的地址了。

二、Consul搭建

這裡使用Docker安裝 ,確保安裝了Docker,執行下面命令。

docker run -d -p 8500:8500 --restart=always --name=consul consul:latest agent -server -bootstrap -ui -node=1 -client='0.0.0.0'

如果是windows環境,到官網https://www.consul.io 下載exe檔案。然後cmd命令切換到consul.exe目錄,執行consul.exe agent -dev 即可啟動。

安裝完,訪問http:ip:8500,看到如下介面則安裝成功。

三、服務註冊

安裝NuGet包 --Consul

appsettings.json增加Consul資訊

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"urls": "http://*:5200",
"Consul": {
"consulAddress": "http://172.16.2.84:8500",
"serviceName": "api",
"currentIp": "172.16.2.9",
"currentPort": "5200"
} }

增加ConsulRegister.cs

 /// <summary>
/// Consul註冊
/// </summary>
public static class ConsulRegister
{
//服務註冊
public static IApplicationBuilder UseConsul(this IApplicationBuilder app, IConfiguration configuration)
{
// 獲取主機生命週期管理介面
var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>(); ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri(configuration["Consul:consulAddress"]);
c.Datacenter = "dc1";
});
string ip = configuration["ip"];
string port = configuration["port"];
string currentIp = configuration["Consul:currentIP"];
string currentPort = configuration["Consul:currentPort"]; ip = string.IsNullOrEmpty(ip) ? currentIp : ip; //當前程式的IP
port = string.IsNullOrEmpty(port) ? currentPort : port; //當前程式的埠
string serviceId = $"service:{ip}:{port}";//服務ID,一個服務是唯一的
//服務註冊
client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = serviceId, //唯一的
Name = configuration["Consul:serviceName"], //組名稱-Group
Address = ip, //ip地址
Port = int.Parse(port), //埠
Tags = new string[] { "api站點" },
Check = new AgentServiceCheck()
{
Interval = TimeSpan.FromSeconds(10),//多久檢查一次心跳
HTTP = $"http://{ip}:{port}/Health/Index",
Timeout = TimeSpan.FromSeconds(5),//超時時間
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5) //服務停止多久後登出服務
} }).Wait();
//應用程式終止時,登出服務
lifetime.ApplicationStopping.Register(() =>
{
client.Agent.ServiceDeregister(serviceId).Wait();
});
return app;
}
}

在Startup.cs中 Configure(IApplicationBuilder app, IWebHostEnvironment env)方法後面加上  app.UseConsul(Configuration);

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
//Consul註冊
app.UseConsul(Configuration);
}

增加健康檢查介面

上面Consul註冊處有一個Check  Http的是心跳健康檢查的地址,需要提供一個介面。

新建HealthController.cs

 /// <summary>
/// consul健康檢查
/// </summary>
public class HealthController : Controller
{
public IActionResult Index()
{
return Ok();
}
}

這樣就配置好了,啟動專案時就會把服務註冊到Consul,我這裡用釋出檔案同時啟動三個做負載。

dotnet ConsulAndOcelot.Demo.ServerB.dll --urls="http://*5201" --ip="172.16.2.9" --port=5201

dotnet ConsulAndOcelot.Demo.ServerB.dll --urls="http://*5202" --ip="172.16.2.9" --port=5202

dotnet ConsulAndOcelot.Demo.ServerB.dll --urls="http://*5203" --ip="172.16.2.9" --port=5203

啟動後,再看一下Consul介面,可以發現服務已成功註冊到Consul。

四、服務發現

另外建一個.NetCore程式。

安裝Nuget包 --Consul

appsettings.json 配置Consul資訊

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Consul": {
"consulAddress": "http://172.16.2.84:8500",
"serviceName": "platform",
"apiServiceName": "api"
}
}

新建ConsulHelper.cs類

  /// <summary>
/// Consul幫助類
/// </summary>
public class ConsulHelper
{
private IConfiguration _configuration;
public ConsulHelper(IConfiguration configuration)
{
_configuration = configuration;
}
/// <summary>
/// 根據服務名稱獲取服務地址
/// </summary>
/// <param name="serviceName"></param>
/// <returns></returns>
public string GetDomainByServiceName(string serviceName)
{
string domain = string.Empty;
//Consul客戶端
using (ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri(_configuration["Consul:consulAddress"]);
c.Datacenter = "dc1"; })
)
{
//根據服務名獲取健康的服務
var queryResult = client.Health.Service(serviceName, string.Empty, true);
var len = queryResult.Result.Response.Length;
//平均策略-多個負載中隨機獲取一個
var node = queryResult.Result.Response[new Random().Next(len)];
domain = $"http://{node.Service.Address}:{node.Service.Port}";
}
return domain;
} /// <summary>
/// 獲取api域名
/// </summary>
/// <returns></returns>
public string GetApiDomain()
{
return GetDomainByServiceName(_configuration["Consul:apiServiceName"]);
}
}

把ConsulHelper注入到IOC容器,Startup.cs中。ConfigureServices(IServiceCollection services)方法加上

 public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddTransient<ConsulHelper>();
}

驗證

 public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ConsulHelper _consulHelper; public HomeController(ILogger<HomeController> logger, ConsulHelper consulHelper)
{
_logger = logger;
_consulHelper = consulHelper;
} public IActionResult Index()
{
///獲取api服務地址
var domain = _consulHelper.GetApiDomain();
ViewBag.domain = domain;
return View();
}
}

執行結果,通過Consul獲得了服務地址,重新整理後會隨獲取到三個負載中的一個。

Consul只負責服務發現,沒有自帶負載均衡策略。用上面的平均策略就可以了,如果想要做成輪詢策略的也可以,不過會增加一些開銷,可以給每組服務定義一個

靜態自增變數index=0,然後獲取的時候,index%服務數取餘,然後index++,這樣就是0%3=0,1%3=1,2%3=2,3%3=0一直迴圈,獲取List[index]服務,index>10000的時候重置為0,這樣就能迴圈的呼叫了。Conul後面配合Ocelot閘道器使用,Ocelot中會自帶幾種負載策略。