.NET Core API 閘道器Ocelot
是一個用.NET Core實現並且開源的API閘道器。路由、請求聚合、認證、鑑權、限流熔斷、負載均衡等功能外,還可以整合Consul做服務發現,整合Polly做服務治理等,並內建了負載均衡器與Service Fabric、Butterfly Tracing整合。
二、工作流程
2.1、基本整合
根據Configuration.json 中配置內容,把接受所有的客戶端請求。路由到對應的下游伺服器進行處理,再將請求結果返回。而這個上下游請求的對應關係也被稱之為路由。
2.2、整合IdentityServer
當我們涉及到授權認證的時候,我們可以跟Identity Server進行結合。當閘道器需要請求認證資訊的時候會與identityServer伺服器進行互動來完成。
2.3、閘道器叢集配置
樂意部署多臺Ocelot閘道器。當然這個時候再多臺閘道器前,你需要一臺負載均衡器。
2.4、Consul服務發現
在Ocelot已經支援簡單的負載功能,當下遊服務存在多個結點的時候,Ocelot能夠承擔起負載均衡的作用。但是沒提供健康檢查,服務的註冊也只能通過手動在配置檔案裡面新增完成。這不夠靈活並且在一定程度下會有風險。這個時候我們就可以用Consul來做服務發現,它能與Ocelot完美結合。
2.5、結合ServiceFabric
三、專案
新建3個webapi:目錄api(Api.Catalog)、訂單api(Api.Ordering)、Ocelot閘道器(ApiGateway.Ocelot);併為每個WebApi專案新增Values控制器(ValuesController),用於區分最終呼叫效果。
Ocelot使用
1、新增Ocelot包依賴:
接下來使用Nuget包管理工具為ApiGateway.Ocelot專案新增Ocelot包引用:
這足以版本,18版本以上的不相容.net core 3.1,可以選擇較低版本的。
2、新增Ocelot配置檔案:【重點】
向ApiGateWay.Ocelot專案新增一個Ocelot.json配置檔案,並修改配置檔案為如下內容。
{ "ReRoutes": [ { "DownstreamPathTemplate": "/api/{everything}", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 1001 }, { "Host": "localhost", "Port": 1002 } ], "UpstreamPathTemplate": "/{everything}", "UpstreamHttpMethod": [ "Get", "Post" ], "LoadBalancerOptions": { "Type": "RoundRobin" }, "AuthenticationOptions": { "AuthenticationProviderKey": "OcelotKey", "AllowedScopes": [] } } ], "Aggregates": [], "GlobalConfiguration": { "RequestIdKey": null, "ServiceDiscoveryProvider": { "Host": "localhost", "Port": 8500, "Type": "Consul", "Token": null, "ConfigurationKey": null }, "RateLimitOptions": { "ClientIdHeader": "ClientId", "QuotaExceededMessage": null, "RateLimitCounterPrefix": "ocelot", "DisableRateLimitHeaders": false, "HttpStatusCode": 429 }, "QoSOptions": { "ExceptionsAllowedBeforeBreaking": 0, "DurationOfBreak": 0, "TimeoutValue": 0 }, "BaseUrl": null, "LoadBalancerOptions": { "Type": "LeastConnection", "Key": null, "Expiry": 0 }, "DownstreamScheme": "http", "HttpHandlerOptions": { "AllowAutoRedirect": false, "UseCookieContainer": false, "UseTracing": false } } }View Code
完整配置可以檢視:官方文件
3、啟用Ocelot中介軟體
3.1、在ApiGateway.Ocelot專案中的Program.cs中載入ocelot.json的配置檔案,如下所示:
.ConfigureAppConfiguration((hostingContext,config) => { config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) .AddJsonFile("appsettings.json", true, true) .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) .AddJsonFile("ocelot.json") .AddEnvironmentVariables(); })View Code
3.2、接下來在Startup.cs檔案中註冊服務
3.3、
把目錄api(Api.Catalog)、訂單api(Api.Ordering)、Ocelot閘道器(ApiGateway.Ocelot)分別設定啟動設定為:http://localhost:5332、http://localhost:5331、http://localhost:5330。
到此Ocelot基本使用完成,接下來驗證下效果