国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

ASP.NET Core 3.x 并發限制的實現代碼

2024-07-10 12:49:40
字體:
來源:轉載
供稿:網友

前言

Microsoft.AspNetCore.ConcurrencyLimiter AspNetCore3.0后增加的,用于傳入的請求進行排隊處理,避免線程池的不足.
我們日常開發中可能常做的給某web服務器配置連接數以及,請求隊列大小,那么今天我們看看如何在通過中間件形式實現一個并發量以及隊列長度限制.

Queue策略

添加Nuget

Install-Package Microsoft.AspNetCore.ConcurrencyLimiter

    public void ConfigureServices(IServiceCollection services)    {      services.AddQueuePolicy(options =>      {        //最大并發請求數        options.MaxConcurrentRequests = 2;        //請求隊列長度限制        options.RequestQueueLimit = 1;      });      services.AddControllers();    }    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)    {      //添加并發限制中間件      app.UseConcurrencyLimiter();      app.Run(async context =>      {        Task.Delay(100).Wait(); // 100ms sync-over-async        await context.Response.WriteAsync("Hello World!");      });      if (env.IsDevelopment())      {        app.UseDeveloperExceptionPage();      }      app.UseHttpsRedirection();      app.UseRouting();      app.UseAuthorization();      app.UseEndpoints(endpoints =>      {        endpoints.MapControllers();      });    }   

通過上面簡單的配置,我們就可以將他引入到我們的代碼中,從而做并發量限制,以及隊列的長度;那么問題來了,他是怎么實現的呢?

 public static IServiceCollection AddQueuePolicy(this IServiceCollection services, Action<QueuePolicyOptions> configure){    services.Configure(configure);    services.AddSingleton<IQueuePolicy, QueuePolicy>();    return services;}

QueuePolicy采用的是SemaphoreSlim信號量設計,SemaphoreSlim、Semaphore(信號量)支持并發多線程進入被保護代碼,對象在初始化時會指定 最大任務數量,當線程請求訪問資源,信號量遞減,而當他們釋放時,信號量計數又遞增。

   /// <summary>    ///   構造方法(初始化Queue策略)    /// </summary>    /// <param name="options"></param>    public QueuePolicy(IOptions<QueuePolicyOptions> options)    {      _maxConcurrentRequests = options.Value.MaxConcurrentRequests;      if (_maxConcurrentRequests <= 0)      {        throw new ArgumentException(nameof(_maxConcurrentRequests), "MaxConcurrentRequests must be a positive integer.");      }      _requestQueueLimit = options.Value.RequestQueueLimit;      if (_requestQueueLimit < 0)      {        throw new ArgumentException(nameof(_requestQueueLimit), "The RequestQueueLimit cannot be a negative number.");      }      //使用SemaphoreSlim來限制任務最大個數      _serverSemaphore = new SemaphoreSlim(_maxConcurrentRequests);    }

ConcurrencyLimiterMiddleware中間件

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 临沭县| 石首市| 马关县| 阿巴嘎旗| 始兴县| 获嘉县| 县级市| 古蔺县| 沈丘县| 湟中县| 泽州县| 东光县| 梅河口市| 北宁市| 四子王旗| 赣榆县| 石泉县| 祥云县| 九寨沟县| 元谋县| 庆元县| 建水县| 绥滨县| 宿州市| 天峨县| 恩平市| 祁阳县| 龙井市| 来安县| 台山市| 磐安县| 绩溪县| 英吉沙县| 县级市| 辛集市| 阳西县| 延安市| 渝中区| 贺州市| 禹城市| 方山县|