一、简介环境 .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中会自带几种负载策略。
源码地址:https://github.com/weixiaolong325/Ocelot-Consul-Polly-Id4.Demo
本文摘自 :https://blog.51cto.com/u