.Net Core使用Ocelot閘道器(一) -負載,限流,熔斷,Header轉換
1.什麼是API閘道器
API閘道器是微服務架構中的唯一入口,它提供一個單獨且統一的API入口用於訪問內部一個或多個API。它可以具有身份驗證,監控,負載均衡,快取,請求分片與管理,靜態響應處理等。API閘道器方式的核心要點是,所有的客戶端和消費端都通過統一的閘道器接入微服務,在閘道器層處理所有的非業務功能。通常,閘道器也是提供REST/HTTP的訪問API。服務端通過API-GW註冊和管理服務。
Ocelot介紹
Ocelot是用.net Core實現的一款開源的閘道器,Ocelot其實就是一組按照順序排列的.net core中介軟體。它接受到請求之後用request builder構建一個HttpRequestMessage物件併發送到下游服務,當下遊請求返回到Ocelot管道時再由一箇中間件將HttpRequestMessage對映到HttpResponse上返回客戶端。
開源地址點選這裡
使用Ocelot傻瓜式轉發
新建三個專案webApi專案,分別命名為ApiGateway,Api_A,Api_B
設定Api_A埠為5001,Api_B埠為5002,ApiGateway為5000
為ApiGateway專案安裝Ocelot,在Nuget中搜索Ocelot或者直接使用Install-Package Ocelot
進行安裝。最新版本為13.8.x支援core3.0。
在ApiGateway新建一個configuration.json
配置檔案。
{ "ReRoutes": [ { //上游Api請求格式 "UpstreamPathTemplate": "/Api_A/{controller}/{action}", //閘道器轉發到下游格式 "DownstreamPathTemplate": "/api/{controller}/{action}", //上下游支援請求方法 "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ], "DownstreamScheme": "http", //下游服務配置 "DownstreamHostAndPorts": [ { //下游地址 "Host": "localhost", //下游埠號 "Port": 5001 } ] }, { "UpstreamPathTemplate": "/Api_B/{controller}/{action}", "DownstreamPathTemplate": "/api/{controller}/{action}", "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ], "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 5002 } ] } ] }
在Startup.cs
的ConfigureServices
和Configure
中配置Ocelot
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddOcelot(new ConfigurationBuilder() .AddJsonFile("configuration.json") .Build()); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseOcelot(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); }
分別為Api_A,和Api_B分別新增一個print介面。
[HttpGet("print")]
public string Print()
{
return "Api_A";
}
[HttpGet("print")]
public string Print()
{
return "Api_B";
}
測試閘道器
啟動三個專案,使用postman來呼叫閘道器
訪問Api_A服務
訪問Api_B服務
可以看到閘道器通過接受到的請求的Url後通過我們的配置自動轉發到了我們想要訪問的服務。
閘道器的負載均衡
當下遊擁有多個節點的時候,我們可以用DownstreamHostAndPorts來配置
{
"UpstreamPathTemplate": "/Api_A/{controller}/{action}",
"DownstreamPathTemplate": "/api/{controller}/{action}",
"DownstreamScheme": "https",
"LoadBalancer": "LeastConnection",
"UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
"DownstreamHostAndPorts": [
{
"Host": "127.0.0.1",
"Port": 5001,
},
{
"Host": "127.00.1",
"Port": 5002,
}
],
}
LoadBalancer是來決定負載的演算法
- LeastConnection:將請求發往最空閒的那個伺服器
- RoundRobin:輪流轉發
- NoLoadBalance:總是發往第一個請求或者是服務發現
限流
限流可以防止上下游伺服器因為過載而崩潰,可以使用RateLimitOptions來配置限流
{
"RateLimitOptions": {
"ClientWhitelist": [“127.0.0.1”],
"EnableRateLimiting": true,
"Period": "5s",
"PeriodTimespan": 1,
"Limit": 10
}
}
- ClientWihteList:白名單,不受限流控制。
- EnableRateLimiting:使用啟用限流。
- Period:限流控制的時間段 1s, 5m, 1h, 1d。
- PeroidTimeSpan:超過限流限制的次數後,需要等待重置的時間(單位是秒)。
- Limit:在限流控制時間段內最大訪問數。
對於除了請求頭中ClientId=127.0.0.1的意外所有求情啟用限流,5秒該api最多10次,如果達到10次需要從第10次請求閉合後等待一秒進行下一次訪問。
超過限流後會返回429狀態碼,並在在返回頭(Response Header)的Retry-After屬性中返回等待重置時間。
限流的預設提示,code碼,和限制標誌都是可以自己配置的
{
"GlobalConfiguration": {
"BaseUrl":"www.baidu.com",
"RateLimitOptions": {
"DisableRateLimitHeaders": false,
"QuotaExceededMessage": "介面限流!",
"HttpStatusCode": 200,
"ClientIdHeader": "ClientId"
}
}
- DisableRateLimitHeaders:是否顯示X-Rate-Limit和Retry-After頭
- QuotaExceededMessage:提示資訊
- HttpStatusCode:狀態碼
- ClientIdHeader:用來設別客戶請求頭,預設為ClientId。
- BaseUrl 閘道器暴露的的地址。
熔斷
熔斷是在下游服務故障或者請求無響應的時候停止將請求轉發到下游服務。
{
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking": 3,
"DurationOfBreak": 20,
"TimeoutValue": 5000
}
}
- ExceptionsAllowedBeforeBreaking:允許多少個異常請求。
- DurationOfBreak:熔斷的時間(秒)。
- TimeoutValue:下游請求的處理時間超過多少則將請求設定為超時。
快取
Ocelot可以對下游請求結果進行快取,主要是依賴於CacheManager來實現的。
{
"FileCacheOptions": {
"TtlSeconds": 60,
"Region": "key"
}
}
- TtlSeconds:快取時間(秒)。
- Region:快取分割槽名
我們可以呼叫Ocelot的API來移除某個區下面的快取 。
請求頭的轉化
Ocelot允許在請求下游服務之前和之後轉換Header.目前Ocelot只支援查詢和替換.
如果們需要轉發給下游的Header重新增一個key/value
{
"UpstreamHeaderTransform": {
"demo": "xxxxxxx"
}
}
如果們需要在返回給客戶端的的Header中新增一個key/value
{
"DownstreamHeaderTransform": {
"demo": "xxxxxxx"
}
}
如果我們需要替換Heaher中某些值
{
//請求
"UpstreamHeaderTransform": {
"demo": "a,b"
},
//響應
"DownstreamHeaderTransform":
{
"demo": "a,b"
}
}
語法是{find},{replace}, 利用b取代a
在Header轉換中可以使用佔位符
- {BaseUrl} - 這個是Ocelot暴露在外的url. 例如http://localhost:5000/.
- {DownstreamBaseUrl} - 這個是下游服務的基本url 例如http://localhost:5001/. 目前這個只在DownstreamHeaderTransform中起作用.
- {TraceId} - 這個是Butterfly的跟蹤id.目前這個也只在DownstreamHeaderTransform中起作用
如果您想將location頭返回給客戶端,可能需要將location更改為Ocelot的地址而不是下游服務地址。 Ocelot可以使用以下配置實現。
{
"DownstreamHeaderTransform": {
"Location": "{DownstreamBaseUrl},{BaseUrl}"
},
}
給Header中新增下游地址
響應的Header中已經替換成BaseUrl了
總結
簡單的實現了通過閘道器來訪問api介面。ocelot功能遠不止這些,之後會實現與IdentityServer的認證鑑權。服務發現。