1.限流(Rate Limiting)
很多時候為了防止DoS攻擊,我們會通過限流方式對上游請求進行限制,以保護下游服務不會負荷過載,為客戶端提供高質量的資源服務。在Ocelot限流項目示例中,通過APIGateway項目路由RateLimitOptions選項可以配置限流。對解決方案的示例APIServices項目Get方法進行限流,文件配置具體代碼如下:
{ "Routes": [ { "DownstreamPathTemplate": "/api/values", "DownstreamScheme": "http", "DownstreamHostAndPorts": [ { "Host": "localhost", "Port": 9001 } ], "UpstreamPathTemplate": "/customers", "UpstreamHttpMethod": [ "Get" ], "RateLimitOptions": { //客戶端白名單。名單中的客戶端不會被限流。 "ClientWhitelist": [], //是否啟用限流。 "EnableRateLimiting": true, //限流時間(1s,5m,1h,1d)。在限流時間內限制請求數,需要等PeriodTimespan時間過去了,才能再次發起請求。 "Period": "1s", //限流時間間隔,限流后多少秒后才可以再次發起請求。 "PeriodTimespan": 3, //限制請求數。 "Limit": 1 } } ], //全局配置,所有下游服務都執行如下限流配置 "GlobalConfiguration": { "RequestIdKey": "OcRequestId", "AdministrationPath": "/administration", "RateLimitOptions": { //是否禁用X-Rate-Limit和Retry-After標頭。 "DisableRateLimitHeaders": false, //限流返回的消息。 "QuotaExceededMessage": "Customize Tips!" } } }
下面來介紹下RateLimitOptions選項幾個參數:
●ClientWhitelist:客戶端白名單。名單中的客戶端不會被限流。
●EnableRateLimiting:是否啟用限流。
●Period:限流時間(1s,5m,1h,1d)。在限流時間內限制請求數,需要等PeriodTimespan時間過去了,才能再次發起請求。
●PeriodTimespan:限流時間間隔,限流后多少秒后才可以再次發起請求。
●Limit:限制請求數。
●DisableRateLimitHeaders:是否禁用X-Rate-Limit和Retry-After標頭。
●QuotaExceededMessage:限流返回的消息。
●HttpStatusCode:限流時候,指定返回的HTTP狀態代碼。
●ClientIdHeader:允許您指定應用於標識客戶端的標頭。默認情況下為“ClientId”。
2.項目演示
2.1APIGateway項目
添加Ocelot服務注入和Logging信息輸出:
public class Startup { public Startup(IWebHostEnvironment env) { var builder = new Microsoft.Extensions.Configuration.ConfigurationBuilder(); builder.SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json") //add configuration.json .AddJsonFile("configuration.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { //輸出Logging信息; services.AddLogging(logging => { logging.AddConsole(); logging.AddDebug(); }); //添加Ocelot服務; services.AddOcelot(Configuration); } public void Configure(IApplicationBuilder app) { //使用Ocelot; app.UseOcelot().Wait(); } }
2.2APIServices項目
項目添加一個Get方法,對應APIGateway項目的路由上下游配置,具體代碼如下:
[Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } }
2.3項目運行
輸入dotnet run --project 項目路徑\項目文件.csproj把兩個項目啟動起來,通過在瀏覽器不斷刷新上游服務地址,會看到如下信息:
根據上述信息可以知道在1秒時間內,如果請求數超過路由配置限制數,那么Ocelot網關就會直接返回429狀態碼和全局給客戶端,不會再轉發到對應下游服務方法去,防止了客戶端惡意攻擊,保證了下游服務不會負荷過載!
參考文獻:
Ocelot官網