.net core 3.1 + consul 搭建服务注册
1.官网www.consul.io下载consul并安装
2.新建一个webapi项目
NuGet安装包Consul
根目录创建类ConsulHelper
public static class ConsulHelper
{
public static void ConsulRegist(this IConfiguration configuration)
{
ConsulClient client = new ConsulClient(c =>
{
c.Address = new Uri("http://localhost:8500/");
c.Datacenter = "dc1";
});
string ip = configuration["ip"];
int port = int.Parse(configuration["port"]);//命令行参数必须传入
int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]);
client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = "service" + port,//唯一的
Name = "UserService",//组名称-Group 湖人
Address = ip,//其实应该写ip地址
Port = port,//不同实例
Tags = new string[] { weight.ToString() },//标签
Check = new AgentServiceCheck()
{
Interval = TimeSpan.FromSeconds(12),//间隔12s一次
HTTP = $"http://{ip}:{port}/api/health",
Timeout = TimeSpan.FromSeconds(5),//检测等待时间
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)//失败后多久移除
}
});
//命令行参数获取
Console.WriteLine($"{ip}:{port}--weight:{weight}");
}
}
Startup.cs类中添加这一行
命令行启动3个实例
dotnet mywebapi.dll --urls=http://:5001 --ip=127.0.0.1 --port=5001
dotnet mywebapi.dll --urls=http://:5002 --ip=127.0.0.1 --port=5002
dotnet mywebapi.dll --urls=http://*:5003 --ip=127.0.0.1 --port=5003
网友评论