最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Asp.NET Core 限流控制(AspNetCoreRateLimit)的實現(xiàn)

 更新時間:2021年03月10日 09:31:03   作者:chaney1992  
這篇文章主要介紹了Asp.NET Core 限流控制(AspNetCoreRateLimit)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

起因:

近期項目中,提供了一些調用頻率較高的api接口,需要保障服務器的穩(wěn)定運行;需要對提供的接口進行限流控制。避免因客戶端頻繁的請求導致服務器的壓力。

一、AspNetCoreRateLimit 介紹

AspNetCoreRateLimit 是一個ASP.NET Core速率限制的解決方案,旨在控制客戶端根據(jù)IP地址或客戶端ID向Web API或MVC應用發(fā)出的請求的速率。AspNetCoreRateLimit包含一個 IpRateLimitMiddlewareClientRateLimitMiddleware ,每個中間件可以根據(jù)不同的場景配置限制允許IP或客戶端,自定義這些限制策略,也可以將限制策略應用在每​​個API URL或具體的HTTP Method上。

二、AspNetCoreRateLimit使用

由上面介紹可知AspNetCoreRateLimit支持了兩種方式:基于 客戶端IP( IpRateLimitMiddleware) 和客戶端ID( ClientRateLimitMiddleware )速率限制  接下來就分別說明使用方式

添加Nuget包引用:

Install-Package AspNetCoreRateLimit 

基于客戶端IP速率限制

1、修改Startup.cs中方法:

public class Startup
{
  public Startup(IConfiguration configuration)
  {
    Configuration = configuration;
  }

  public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.
  public void ConfigureServices(IServiceCollection services)
  {
    //需要從加載配置文件appsettings.json
    services.AddOptions();
    //需要存儲速率限制計算器和ip規(guī)則
    services.AddMemoryCache();

    //從appsettings.json中加載常規(guī)配置,IpRateLimiting與配置文件中節(jié)點對應
    services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));

    //從appsettings.json中加載Ip規(guī)則
    services.Configure<IpRateLimitPolicies>(Configuration.GetSection("IpRateLimitPolicies"));

    //注入計數(shù)器和規(guī)則存儲
    services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
    services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

    services.AddControllers();

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    //配置(解析器、計數(shù)器密鑰生成器)
    services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();

    //Other Code
  }

  // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
    //Other Code

    app.UseRouting();

    app.UseAuthorization();
     //啟用客戶端IP限制速率
    app.UseIpRateLimiting();

    app.UseEndpoints(endpoints =>
    {
      endpoints.MapControllers();
    });
  }
}

2、在appsettings.json中添加通用配置項節(jié)點:(IpRateLimiting節(jié)點與Startup中取的節(jié)點對應)

"IpRateLimiting": {
 //false,則全局將應用限制,并且僅應用具有作為端點的規(guī)則*。例如,如果您設置每秒5次調用的限制,則對任何端點的任何HTTP調用都將計入該限制
 //true, 則限制將應用于每個端點,如{HTTP_Verb}{PATH}。例如,如果您為*:/api/values客戶端設置每秒5個呼叫的限制,
 "EnableEndpointRateLimiting": false,
 //false,拒絕的API調用不會添加到調用次數(shù)計數(shù)器上;如 客戶端每秒發(fā)出3個請求并且您設置了每秒一個調用的限制,則每分鐘或每天計數(shù)器等其他限制將僅記錄第一個調用,即成功的API調用。如果您希望被拒絕的API調用計入其他時間的顯示(分鐘,小時等) //,則必須設置StackBlockedRequests為true。
 "StackBlockedRequests": false,
 //Kestrel 服務器背后是一個反向代理,如果你的代理服務器使用不同的頁眉然后提取客戶端IP X-Real-IP使用此選項來設置
 "RealIpHeader": "X-Real-IP",
 //取白名單的客戶端ID。如果此標頭中存在客戶端ID并且與ClientWhitelist中指定的值匹配,則不應用速率限制。
 "ClientIdHeader": "X-ClientId",
 //限制狀態(tài)碼
 "HttpStatusCode": 429,
 ////IP白名單:支持Ip v4和v6 
 //"IpWhitelist": [ "127.0.0.1", "::1/10", "192.168.0.0/24" ],
 ////端點白名單
 //"EndpointWhitelist": [ "get:/api/license", "*:/api/status" ],
 ////客戶端白名單
 //"ClientWhitelist": [ "dev-id-1", "dev-id-2" ],
 //通用規(guī)則
 "GeneralRules": [
  {
   //端點路徑
   "Endpoint": "*",
   //時間段,格式:{數(shù)字}{單位};可使用單位:s, m, h, d
   "Period": "1s",
   //限制
   "Limit": 2
  },   //15分鐘只能調用100次
  {"Endpoint": "*","Period": "15m","Limit": 100},   //12H只能調用1000
  {"Endpoint": "*","Period": "12h","Limit": 1000},   //7天只能調用10000次
  {"Endpoint": "*","Period": "7d","Limit": 10000}
 ]
}

配置節(jié)點已添加相應注釋信息。

規(guī)則設置格式:

端點格式: {HTTP_Verb}:{PATH} ,您可以使用asterix符號來定位任何HTTP謂詞。

期間格式: {INT}{PERIOD_TYPE} ,您可以使用以下期間類型之一: s, m, h, d 。

限制格式: {LONG}

3、特點Ip限制規(guī)則設置,在appsettings.json中添加 IP規(guī)則配置節(jié)點

"IpRateLimitPolicies": {
 //ip規(guī)則
 "IpRules": [
  {
   //IP
   "Ip": "84.247.85.224",
   //規(guī)則內容
   "Rules": [
    //1s請求10次
    {"Endpoint": "*","Period": "1s","Limit": 10},
    //15分鐘請求200次
    {"Endpoint": "*","Period": "15m","Limit": 200}
   ]
  },
  {
   //ip支持設置多個
   "Ip": "192.168.3.22/25",
   "Rules": [
    //1秒請求5次
    {"Endpoint": "*","Period": "1s","Limit": 5},
    //15分鐘請求150次
    {"Endpoint": "*","Period": "15m","Limit": 150},
    //12小時請求500次
    {"Endpoint": "*","Period": "12h","Limit": 500}
   ]
  }
 ]
}

基于客戶端ID速率限制

1、修改Startup文件:

public void ConfigureServices(IServiceCollection services)
{
  //需要從加載配置文件appsettings.json
  services.AddOptions();

  //需要存儲速率限制計算器和ip規(guī)則
  services.AddMemoryCache();

  //從appsettings.json中加載常規(guī)配置
  services.Configure<ClientRateLimitOptions>(Configuration.GetSection("IPRateLimiting"));

  //從appsettings.json中加載客戶端規(guī)則
  services.Configure<ClientRateLimitPolicies>(Configuration.GetSection("ClientRateLimitPolicies"));

  //注入計數(shù)器和規(guī)則存儲
  services.AddSingleton<IClientPolicyStore, MemoryCacheClientPolicyStore>();
  services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

  
  services.AddControllers();

    // https://github.com/aspnet/Hosting/issues/793
    // the IHttpContextAccessor service is not registered by default.
    //注入計數(shù)器和規(guī)則存儲
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    //配置(解析器、計數(shù)器密鑰生成器)
    services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //啟用客戶端限制
  app.UseClientRateLimiting();

  app.UseMvc();
}

2、通用配置采用IP限制相同配置,添加客戶端限制配置:

//客戶端限制設置
"ClientRateLimitPolicies": {
 "ClientRules": [
  {
   //客戶端id
   "ClientId": "client-id-1",
   "Rules": [
    {"Endpoint": "*","Period": "1s","Limit": 10},
    {"Endpoint": "*","Period": "15m","Limit": 200}
   ]
  },
  {
   "ClientId": "client-id-2",
   "Rules": [
    {"Endpoint": "*","Period": "1s","Limit": 5},
    {"Endpoint": "*","Period": "15m","Limit": 150},
    {"Endpoint": "*","Period": "12h","Limit": 500}
   ]
  }
 ]
}

3、調用結果:

設置規(guī)則:1s只能調用一次:首次調用

調用第二次:自定義返回內容

三、其他

 運行時更新速率限制

添加 IpRateLimitController控制器:

/// <summary>
/// IP限制控制器
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class IpRateLimitController : ControllerBase
{

  private readonly IpRateLimitOptions _options;
  private readonly IIpPolicyStore _ipPolicyStore;

  /// <summary>
  /// 
  /// </summary>
  /// <param name="optionsAccessor"></param>
  /// <param name="ipPolicyStore"></param>
  public IpRateLimitController(IOptions<IpRateLimitOptions> optionsAccessor, IIpPolicyStore ipPolicyStore)
  {
    _options = optionsAccessor.Value;
    _ipPolicyStore = ipPolicyStore;
  }

  /// <summary>
  /// 獲取限制規(guī)則
  /// </summary>
  /// <returns></returns>
  [HttpGet]
  public async Task<IpRateLimitPolicies> Get()
  {
    return await _ipPolicyStore.GetAsync(_options.IpPolicyPrefix);
  }

  /// <summary>
  /// 
  /// </summary>
  [HttpPost]
  public async Task Post(IpRateLimitPolicy ipRate)
  {
    var pol = await _ipPolicyStore.GetAsync(_options.IpPolicyPrefix);
    if (ipRate != null)
    {
      pol.IpRules.Add(ipRate);
      await _ipPolicyStore.SetAsync(_options.IpPolicyPrefix, pol);
    }
  }
}

分布式部署時,需要將速率限制計算器和ip規(guī)則存儲到分布式緩存中如Redis

修改注入對象

// inject counter and rules distributed cache stores
services.AddSingleton<IClientPolicyStore, DistributedCacheClientPolicyStore>();
services.AddSingleton<IRateLimitCounterStore,DistributedCacheRateLimitCounterStore>();

添加Nuget包  Microsoft.Extensions.Caching.StackExchangeRedis 

在Startup中設置Redis連接

services.AddStackExchangeRedisCache(options =>
{
  options.ConfigurationOptions = new ConfigurationOptions
  {
    //silently retry in the background if the Redis connection is temporarily down
    AbortOnConnectFail = false
  };
  options.Configuration = "localhost:6379";
  options.InstanceName = "AspNetRateLimit";
});

限制時自定義相應結果:

//請求返回
  "QuotaExceededResponse": {
   "Content": "{{\"code\":429,\"msg\":\"Visit too frequently, please try again later\",\"data\":null}}",
   "ContentType": "application/json;utf-8",
   "StatusCode": 429
  },

調用時返回結果:

其他:

示例代碼:https://github.com/cwsheng/WebAPIVersionDemo

到此這篇關于Asp.NET Core 限流控制(AspNetCoreRateLimit)的實現(xiàn)的文章就介紹到這了,更多相關Asp.NET Core 限流控制內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

大英县| 昌乐县| 石泉县| 噶尔县| 新丰县| 章丘市| 武山县| 湾仔区| 都兰县| 昆明市| 中方县| 商南县| 麦盖提县| 抚松县| 麻江县| 弋阳县| 贵港市| 陇南市| 大英县| 阿荣旗| 鸡泽县| 交口县| 阿克| 杨浦区| 阳山县| 洱源县| 尉氏县| 栖霞市| 洛隆县| 临洮县| 渭源县| 墨玉县| 江安县| 巴中市| 无锡市| 苗栗市| 云阳县| 革吉县| 武城县| 抚宁县| 昌宁县|