Consul+Ocelot配置微服务
1、下载consul 地址 Install | Consul | HashiCorp Developer
解压之后

启动consul:终端运行 consul agent -dev -client 0.0.0.0 -ui
2、写一个扩展方法
需要安装的包
- Ocelot
- Ocelot.Provider.Consul

1 public static void ConsulExtend(this IConfiguration configuration, string serviceName) 2 { 3 ConsulClient client = new(m => 4 { 5 m.Address = new Uri("http://10.10.10.10:8500/");//对应服务器的地址:consul的端口 6 m.Datacenter = "dc1"; 7 }); 8 9 //启动的时候在consul中注册实例服务 10 //在consul中注册的ip, port 11 string ip = configuration["ip"]; 12 int port = int.Parse(configuration["port"]); 13 int weight = string.IsNullOrWhiteSpace(configuration["weight"]) ? 1 : int.Parse(configuration["weight"]); 14 client.Agent.ServiceRegister(new AgentServiceRegistration() 15 { 16 ID = "service" + Guid.NewGuid(),//唯一的 17 Name = serviceName,//组(服务)名称(动态) 18 Address = ip, 19 Port = port,//不同的端口=>不同的实例 20 Tags = new string[] { weight.ToString() },//标签 21 Check = new AgentServiceCheck()//服务健康检查 22 { 23 Interval = TimeSpan.FromSeconds(12),//间隔1s一次 检查 24 HTTP = $"http://{ip}:{port}/Api/Health/Check", 25 Timeout = TimeSpan.FromSeconds(5),//检测等待时间 26 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)//失败后多久移除 27 } 28 }); 29 Console.WriteLine($"{ip}:{port}--weight:{weight}"); 30 }
上面的方法带了一个参数,用来注册在consul中的服务
当服务启动的时候 把自身对应的服务名称传递过来

{ //*************************多实例负载均衡+Consul*****************************
"Routes": [
//OrderWrite
{
//GeteWay转发=>Downstream
"DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
"DownstreamScheme": "http",
//http://localhost:6299/T5/User/GetCustomerUser
"UpstreamPathTemplate": "/OrderWrite/{url}", //网关地址--url变量 冲突的还可以加权重Priority
"UpstreamHttpMethod": [ "Get", "Post" ],
"UseServiceDiscovery": true, //使用服务发现
"ServiceName": "OrderWrite", //Consul服务名称
"LoadBalancerOptions": {
"Type": "RoundRobin" //轮询 //"LeastConnection":最少连接数服务器 "NoloadBalance":不负载均衡 "CookieStickySession":会话粘滞
}
}
],
"GlobalConfiguration": {
//"BaseUrl": "http://127.0.0.1:6299",
"ServiceDiscoveryProvider": {
"Host": "10.10.10.10", //上文中consul的地址
"Port": 8500,
"Type": "Consul" //由Consul提供服务发现,每次请求去Consul
}
//"ServiceDiscoveryProvider": {
// "Host": "localhost",
// "Port": 8500,
// "Type": "PollConsul", //由Consul提供服务发现,每次请求去Consul
// "PollingInterval": 1000//轮询Consul,评率毫秒--down是不知道的
//}
}
//*************************多实例负载均衡+Consul*****************************
}

网关的Program

end...

浙公网安备 33010602011771号