NetCore+Consul服務註冊+Ocelot閘道器配置
阿新 • • 發佈:2022-05-18
Consul 是 HashiCorp 公司推出的開源工具,用於實現分散式系統的服務發現與配置。
Ocelot是一個用.NET Core實現並且開源的API閘道器,它功能強大,除了路由、請求聚合、負載均衡等功能外,還可以整合Consul做服務發現,整合Polly做服務治理等; 相關功能只需簡單的配置即可實現。
1:Consul
官網下載Consul,然後啟動
consul agent -dev
2:新建一個webapi專案,nuget引入consul。
新建一個類,ConsulRegister用於服務註冊。
public static class RegisterHelper {public static void RegisterClient(this IConfiguration configuration, IHostApplicationLifetime lifetime) { ConsulClient client = new ConsulClient(c => { c.Address = new Uri("http://127.0.0.1:8500"); c.Datacenter = "fanlin"; });string ip = configuration["ip"]; int port = Convert.ToInt32(configuration["port"]); string serviceName = configuration["ServiceName"]; var registerion = new AgentServiceRegistration() { Address = ip, Port = port, ID= "fanlin:" + Guid.NewGuid().ToString(), Name = serviceName }; //生命週期 //註冊 lifetime.ApplicationStarted.Register(() => { client.Agent.ServiceRegister(registerion).Wait(); Console.WriteLine("註冊" + registerion.Address + ":" + registerion.Port); }); //登出 lifetime.ApplicationStopping.Register(() => { client.Agent.ServiceDeregister(registerion.ID).Wait();//服務停止時取消註冊 Console.WriteLine("登出" + registerion.Address + ":" + registerion.Port); }); //登出 lifetime.ApplicationStopped.Register(() => { client.Agent.ServiceDeregister(registerion.ID).Wait();//服務停止時取消註冊 Console.WriteLine("登出" + registerion.Address + ":" + registerion.Port); }); } }
然後在startup裡面Configure方法引用
Configuration.RegisterClient(lifetime);
3:到專案的資料夾下,通過cmd方式啟動,指定埠和ip以及服務名稱
dotnet ConsulRegister.dll --urls="http://*:8111" --ip =127.0.0.1 --port=8111 --ServiceName=A dotnet ConsulRegister.dll --urls="http://*:8112" --ip =127.0.0.1 --port=8112 --ServiceName=B
4:訪問localhost:8500可以發現有兩個我們的節點
5:ocelot
新建一個專案,nuget引入ocelot和Ocelot.Provider.Consul。然後新建一個ocelot.json,內容如下
{ "ReRoutes": [ //配置路由資訊 { "UseServiceDiscovery": true, "DownstreamPathTemplate": "/{url}", //指定了下游的url及使用的通訊協議,{url}是通配的意思 "DownstreamScheme": "http", //下游服務http schema "ServiceName": "A", //服務名 "LoadBalancerOptions": { "Type": "LeastConnection" }, "UpstreamPathTemplate": "/ServiceA/{url}", //上游也就是使用者輸入的請求Url模板 "UpstreamHttpMethod": [ "Get" ] //上游請求http方法,可使用陣列 }, { "UseServiceDiscovery": true, "DownstreamPathTemplate": "/{url}", //指定了下游的url及使用的通訊協議,{url}是通配的意思 "DownstreamScheme": "http", "ServiceName": "B", "LoadBalancerOptions": { "Type": "LeastConnection" }, "UpstreamPathTemplate": "/ServiceB/{url}", "UpstreamHttpMethod": [ "Get" ] } ], //閘道器配置 "GlobalConfiguration": { "BaseUrl": "https://localhost:44355/", //閘道器地址 "ServiceDiscoveryProvider": { "Host": "localhost", //請求域名 "Port": 8500, //埠 "Type": "Consul" //型別 } } }
然後啟動。這時候我們
https://localhost:44355/ServiceB/api/Health/HealthCheck 就會訪問到B服務的介面