国产探花免费观看_亚洲丰满少妇自慰呻吟_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中間件

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建湖县| 长垣县| 四平市| 湖州市| 巴塘县| 平利县| 桃园县| 延川县| 金坛市| 长白| 塔河县| 夹江县| 大竹县| 崇左市| 德令哈市| 阳谷县| 邓州市| 开封县| 常山县| 高青县| 崇明县| 搜索| 永州市| 禹州市| 岑溪市| 浦江县| 连城县| 武功县| 佳木斯市| 西平县| 社旗县| 晴隆县| 华亭县| 张掖市| 鹤庆县| 清丰县| 大关县| 广昌县| 仁寿县| 临沧市| 敦煌市|