1.配置微服务
1)appsettings.json
"Consul": {
"ServiceName": "cms",
"IP": "127.0.0.1",
"Weight": "1",
"Port": "5017"
}
2)ConsulBuilderExtensions.cs
using Consul;
namespace Micro.Cms
{
public static class ConsulBuilderExtensions
{
public static void ConsulExtend(this IConfiguration configuration, string serviceName)
{
ConsulClient client = new(m =>
{
//对应服务器的地址:consul的端口
m.Address = new Uri("http://127.0.0.1:8500/");
m.Datacenter = "cms";
});
//启动的时候在consul中注册实例服务
//在consul中注册的ip, port
string ServiceName = configuration.GetSection("Consul")["ServiceName"];
string ip = configuration.GetSection("Consul")["IP"];
int port = int.Parse(configuration.GetSection("Consul")["Port"]);
int weight = int.Parse(configuration.GetSection("Consul")["Weight"]);
client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = $"{configuration["ServiceName"]}-{Guid.NewGuid()}",//唯一的
Name = serviceName,//组(服务)名称(动态)
Address = ip,
Port = port,//不同的端口=>不同的实例
Tags = new string[] { weight.ToString() },//标签
Check = new AgentServiceCheck()//服务健康检查
{
Interval = TimeSpan.FromSeconds(12),//间隔1s一次 检查
HTTP = $"http://{ip}:{port}/api/health/check",
Timeout = TimeSpan.FromSeconds(5),//检测等待时间
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)//失败后多久移除
}
});
Console.WriteLine($"{ip}:{port}--weight:{weight}");
}
}
}
3)Program.cs
//注册服务Consul名称
builder.Configuration.ConsulExtend(builder.Configuration.GetSection("Consul")["ServiceName"]);