Ocelot Api网关教程(9)- QoS
本文介紹Ocelot中的QoS(Quality of Service),其使用了Polly對超時等請求下游失敗等情況進行熔斷。
1、添加Nuget包
添加?Ocelot.Provider.Polly?到OcelotGetway項目中
2、修改?Startup.ConfigureServices?如下來添加Polly:
services.AddOcelot(new ConfigurationBuilder()
.AddJsonFile("configuration.json")
.Build())
.AddConsul()
.AddPolly()
.AddCacheManager(x => x.WithDictionaryHandle())
.AddAdministration("/administration", "secret");
3、在WebApiA中添加一個SlowController,并添加如下代碼:
using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;
namespace WebApiA.Controllers
{
public class SlowController : Controller
{
[Produces("application/json")]
[Route("api/[controller]/[action]")]
public async Task<string> GetName()
{
await Task.Delay(6000);
return "Jonathan";
}
}
}
其中?GetName?延時6秒返回。
4、在configuration.json的?ReRoutes?節點添加一個新的路由來訪問剛才添加的api方法
{"DownstreamPathTemplate": "/api/Slow/GetName",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5001
}
],
"UpstreamPathTemplate": "/GetName",
"UpstreamHttpMethod": [ "Get" ],
"QoSOptions": {
"ExceptionsAllowedBeforeBreaking":3,
"DurationOfBreak":60000,
"TimeoutValue": 1000
}
}
其中通過?QoSOptions?對該路由添加QoS,對其中的3個屬性解釋如下:
ExceptionsAllowedBeforeBreaking:發生幾次請求異常(比如超時)后進行熔斷,該值必須大于0
DurationOfBreak:熔斷時間(單位:毫秒)
TimeoutValue:下游請求超時時間(單位:毫秒,默認90秒)
用一句話描述上述配置:對http://localhost:5001/api/Slow/GetName請求超過1s將會超時,發生三次超時后保持60s熔斷。
運行WebApiA與OcelotGetway項目,然后請求http://localhost:5000/GetName多次:
可以看到在前3次請求,Time在1000ms之后返回503,在第四次以后發生熔斷,請求后立即(Time在100ms左右)返回503。
官方文檔中說可以只配置?TimeoutValue?而不配置其它兩個來達到修改超時時間的功能,如下:
"TimeoutValue":5000
}
該配置存在bug,因為如上配置?ExceptionsAllowedBeforeBreaking?將會為0,將會觸發Polly配置異常,我已經向Ocelot提交了一個Pull Request來修復該問題,并且已經被合并到主分支中,預計在下一個版本中該問題將不會存在。
如果你現在想修改超時時間,但是又不想使用熔斷,可以配置如下:
"ExceptionsAllowedBeforeBreaking":10000,
"DurationOfBreak": 1,
"TimeoutValue": 1000
}
在發生很多次異常才會進行熔斷,并且立即從熔斷中恢復。
相關文章:
.Netcore 2.0 Ocelot Api網關教程(番外篇)- Ocelot v13.x升級
.Netcore 2.0 Ocelot Api網關教程(6)- 配置管理
.Netcore 2.0 Ocelot Api網關教程(7)- 限流
.Netcore 2.0 Ocelot Api網關教程(8)- 緩存
【.NET Core項目實戰-統一認證平臺】第十六章 網關篇-Ocelot集成RPC服務
ocelot 自定義認證和授權
eShopOnContainers 知多少[9]:Ocelot gateways
使用Ocelot、IdentityServer4、Spring Cloud Eureka搭建微服務網關:(一)
原文地址:https://www.jianshu.com/p/c7f5f9515962
.NET社區新聞,深度好文,歡迎訪問公眾號文章匯總 http://www.csharpkit.com
總結
以上是生活随笔為你收集整理的Ocelot Api网关教程(9)- QoS的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于IdentityServer的系统对
- 下一篇: Abp框架准备加入.NET Founda