参考文章:
https://www.cnblogs.com/edisonchou/p/9124985.html
上面的文章已经写的非常好了,我在这就再简单的写一下,参考文章里的代码有个地方需要注意IApplicationLifetime这个需要替换一下 那个是老版本的.net core用的,替换成IHostApplicationLifetime同样是在Microsoft.Extensions.Hosting里
Consul是Go语言写的,在.net core的web程序里面主要是用来做服务的注册和发现
首先下载Consul
https://www.consul.io/downloads
然后解压直接用
这里是dev环境 更多具体的使用再百度
按回车 然后输入一下网址
http://localhost:8500
然后开始整代码
新建一个扩展方法:
using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using System;
namespace Hotel.Web.API.Extension
{
public static class AppBuilderExtensions
{
public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IHostApplicationLifetime lifetime, ServiceEntity serviceEntity)
{
var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//请求注册的 Consul 地址
var httpCheck = new AgentServiceCheck()
{
DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔
HTTP = $"http://{serviceEntity.IP}:{serviceEntity.Port}/api/Health",//健康检查地址
Timeout = TimeSpan.FromSeconds(5)
};
// Register service with consul
var registration = new AgentServiceRegistration()
{
Checks = new[] { httpCheck },
ID = Guid.NewGuid().ToString(),
Name = serviceEntity.ServiceName,
Address = serviceEntity.IP,
Port = serviceEntity.Port,
Tags = new[] { $"urlprefix-/{serviceEntity.ServiceName}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
};
consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
lifetime.ApplicationStopping.Register(() =>
{
consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
});
return app;
}
}
}
加个类
public class ServiceEntity
{
public string IP { get; set; }
public int Port { get; set; }
public string ServiceName { get; set; }
public string ConsulIP { get; set; }
public int ConsulPort { get; set; }
}
配置文件里添加如下配置 这里加在appSetting.json里了
"Consul": {
"IP": "localhost",
"Port": 8002,
"ServiceName": "hotel_api",
"ConsulIP": "localhost",
"ConsulPort": 8500
}
然后在Startup类里的Configure方法里添加
// register this service
ServiceEntity serviceEntity = new ServiceEntity
{
IP = "localhost",
Port = Convert.ToInt32(Configuration["Consul:Port"]),
ServiceName = Configuration["Consul:ServiceName"],
ConsulIP = Configuration["Consul:ConsulIP"],
ConsulPort = Convert.ToInt32(Configuration["Consul:ConsulPort"])
};
app.RegisterConsul(lifetime, serviceEntity);
注意 lifetime 这个需要在Configure方法的参数里加个参数Microsoft.Extensions.Hosting.IHostApplicationLifetime lifetime
现在就可以了 运行程序
完事