- 在微服务的依赖上加上Consul包
- 配置appSettings.json配置文件如下
//consul配置
//1.服务名
"ServiceName": "Order",
//2.服务地址,本地
"IP": "localhost",
//3.这个端口号需要和 Properties文件夹下的 launchSettings.json中配置的 applicationUrl一样
"Port": 9001,
//4.consul 的健康检查地址(写一个/api/Health的controller)
"ServiceHealthCheck": "http://localhost:9001/api/Health",
//5.consul 地址
"ConsulAddress": "http://localhost:8500",
- 创建一个注册Consul的注册类(这里读取的appsettings.json的配置信息)
public static class ConsulRegister
{
/// <summary>
/// 扩展方法 将服务注册到consul
/// </summary>
/// <param name="configuration"></param>
public static void RegisterConsul(this IConfiguration configuration)
{
#region 注册consul
string ip = configuration["IP"];
int port = int.Parse(configuration["Port"]);
ConsulClient client = new ConsulClient(obj =>
{
//http://127.0.0.1:8500
obj.Address = new Uri(configuration["ConsulAddress"]);
obj.Datacenter = "dcl";
});
//向consul注册服务
Task<WriteResult> result = client.Agent.ServiceRegister(new AgentServiceRegistration()
{
ID = configuration["ServiceName"] + "_" + Guid.NewGuid(),//服务编号,不能重复,用guid最简单
Name = configuration["ServiceName"],//服务名称
Address = ip,
Port = port,
Tags = new string[] { },//可以用来设置权重
Check = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务停止多久后取消
Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者成为心跳间隔
HTTP = configuration["ServiceHealthCheck"],//健康检查地址
Timeout = TimeSpan.FromSeconds(5)//检测时最长等待时间
}
});
#endregion
}
}
- 在Program.cs中配置注册信息(RegisterConsul()方法就是上面的注册类中的静态方法)
app.Configuration.RegisterConsul();