Consul的服务注册与发现
1.下载
https://www.consul.io/downloads.html
2.解压并在Path中增加目录的环境变量
3.在目录下输入consul agent -dev 启动
4.启动成功后在 浏览器中输入http://localhost:8500/ui/dc1/services

有以上界面表示 启动成功
在项目中添加包Consul
添加Consul帮助类
public static class ConsulHelp
{
public static void ConsulRegist (this IConfiguration configuration)
{
string ip = configuration["ip"];
int port = int.Parse(configuration["port"]);
using (ConsulClient client = new ConsulClient(operation =>
{
operation.Address = new Uri("http://localhost:8500/");
operation.Datacenter = "dcl";
}))
{
//添加ConsulClient
var age = new AgentServiceRegistration()
{
ID = "service" + Guid.NewGuid(), //唯一名
Name = "WuJinHuaService",//组名
Address = ip,
Port = port,
Check = new AgentServiceCheck() //配置心跳检查
{
Interval = TimeSpan.FromSeconds(20),
HTTP = $"http://{ip}:{port}/api/v1/ConsulCheck/CheckConsul",
Timeout = TimeSpan.FromSeconds(5),
DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(90),//服务检测失败的时 多久注销服务
}
};
client.Agent.ServiceRegister(age).Wait();
Console.WriteLine(age.Check.HTTP);
}
Console.WriteLine($"{ip}:{port}注册成功");
}
}
在Configure 中注册 this.Configuration.ConsulRegist();
结合ocelot
新增一个WebApi工程 引入以下包

增加ocelot.json 配置文件
{
"Routes": [
{
"DownstreamPathTemplate": "/api/v1/{url}", //下游
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/WuJinHua/{url}", //上游
"UpstreamHttpMethod": [ "Get", "Post" ],
"ServiceName": "WuJinHuaService", //Consul服务名
"LoadBalancerOptions": {
"Type": "RoundRobin"
}
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost:6299",
"ServiceDiscoveryProvider": {
"Scheme": "http",
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
}
}
ConfigureServices 中增加 services.AddOcelot().AddConsul();
Configure中增加 app.UseOcelot().Wait();

浙公网安备 33010602011771号