.NET Core微服務二:Ocelot API閘道器
.NET Core微服務一:Consul服務中心
.NET Core微服務二:Ocelot API閘道器
.NET Core微服務三:polly熔斷與降級
本文的專案程式碼,在文章結尾處可以下載。
本文使用的環境:Windows10 64位 + VS 2019 + .NET Core 2.1 + Ocelot 8.0.8
Ocelot 相關地址:
https://github.com/ThreeMammals/Ocelot
https://ocelot.readthedocs.io/en/latest/introduction/gettingstarted.html
截至2020.02.03發現:
Ocelot單獨使用的時候,用目前最新版14.0.3沒什麼問題,看“Ocelot的簡單使用”這篇文章。
在與Consul配合使用的時候,環境要是.NET Core 2.1 + Ocelot 8.0.8這樣組合就正常,
高於這樣的版本,要麼出現“404”,要麼出現“目標拒絕”的錯誤,又或者其它莫名異常;
並且也有個問題,如果一個服務有多臺伺服器,那Ocelot的負載均衡只會連線到一臺伺服器。
或許是我操作的方式不對,反正目前我沒有找到解決方法,有知道的大神麻煩告知下。
承接著“.NET Core微服務一:Consul服務中心”這篇文章,通過cmd執行起“Student”和“Teacher”服務,接下來就是建立閘道器專案
一、新建webapi專案,命名為“Ocelot_Consul”,去掉HTTPS勾選,不需要Controller,改為控制檯方式啟動
二、開啟程式包管理器控制檯,執行命令:
Install-Package Ocelot -Version 8.0.8
三、在專案根目錄下,新建配置檔案“ocelot.json”
"LoadBalancer"負載均衡型別:
RoundRobin:輪詢機制,迴圈找到可以用的服務
LeastConnection:最少連線數,跟蹤發現現在有最少請求或處理的可用服務
NoLoadBalancer:不使用負載均衡,直接訪問第一個發現的可用的服務
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/Default/GetList", "DownstreamScheme": "http", "UpstreamPathTemplate": "/api/v1/Student/GetList", "UpstreamHttpMethod": [ "Get" ], "ServiceName": "Student", "LoadBalancer": "RoundRobin", "UseServiceDiscovery": true // , //"RateLimitOptions": { // "ClientWhitelist": [], //白名單 // "EnableRateLimiting": true, //是否限流 // "Period": "30s", //指定一個時間 // "PeriodTimespan": 10, //多少時間後,可以重新請求。 // "Limit": 5 //在Period的指定時間內,最多請求次數 //} }, { "DownstreamPathTemplate": "/api/Default/GetList", "DownstreamScheme": "http", "UpstreamPathTemplate": "/api/v1/Teacher/GetList", "UpstreamHttpMethod": [ "Get" ], "ServiceName": "Teacher", "LoadBalancer": "RoundRobin", "UseServiceDiscovery": true } ], "GlobalConfiguration": { "ServiceDiscoveryProvider": { "Host": "127.0.0.1", "Port": 8500 } } }
四、在Program.cs的CreateHostBuilder中加入
.ConfigureAppConfiguration(conf => { conf.AddJsonFile("ocelot.json", false, true); })
五、找到Startup.cs
在ConfigureServices中加入:
services.AddOcelot();
在Configure中加入:
app.UseOcelot().Wait();
注:較高的Ocelot版本,需要“Ocelot.Provider.Consul”元件,ConfigureServices會不一樣:
services.AddOcelot().AddConsul().AddConfigStoredInConsul();
六、通過VS啟動“Ocelot_Consul”,通過“ocelot.json”配置的對外的路由
“Student”服務的訪問地址為:http://localhost:5000/api/v1/Student/GetList
“Teacher”服務的訪問地址為:http://localhost:5000/api/v1/Teacher/GetList
程式碼:https://files.cnblogs.com/files/shousiji/Ocelot_Consul.rar
&n