ASP.NET Core Web API 介面限流

0611163發表於2023-03-09

前言

ASP.NET Core Web API 介面限流、限制介面併發數量,我也不知道自己寫的有沒有問題,拋磚引玉、歡迎來噴!

需求

  1. 寫了一個介面,引數可以傳多個人員,也可以傳單個人員,時間範圍限制最長一個月。簡單來說,當傳單個人員時,介面耗時很短,當傳多個人員時,一般人員會較多,介面耗時較長,一般耗時幾秒。
  2. 當傳多個人員時,併發量高時,介面的耗時就很長了,比如100個使用者併發請求,耗時可長達幾十秒,甚至1分鐘。
  3. 所以需求是,當傳單個人員時,不限制。當傳多個人員時,限制併發數量。如果併發使用者數少於限制數,那麼所有使用者都能成功。如果併發使用者數,超出限制數,那麼超出的使用者請求失敗,並提示"當前進行XXX查詢的使用者太多,請稍後再試"。
  4. 這樣也可以減輕被請求的ES叢集的壓力。

說明

  1. 使用的是.NET6
  2. 我知道有人寫好了RateLimit中介軟體,但我暫時還沒有學會怎麼使用,能否滿足我的需求,所以先自己實現一下。

效果截圖

下面是使用jMeter併發測試時,打的介面日誌:

程式碼

RateLimitInterface

介面引數的實體類要繼承該介面

using JsonA = Newtonsoft.Json;
using JsonB = System.Text.Json.Serialization;

namespace Utils
{
    /// <summary>
    /// 限速介面
    /// </summary>
    public interface RateLimitInterface
    {
        /// <summary>
        /// 是否限速
        /// </summary>
        [JsonA.JsonIgnore]
        [JsonB.JsonIgnore]
        bool IsLimit { get; }
    }
}

介面引數實體類

繼承RateLimitInterface介面,並實現IsLimit屬性

public class XxxPostData : RateLimitInterface
{
    ...省略

    /// <summary>
    /// 是否限速
    /// </summary>
    [JsonA.JsonIgnore]
    [JsonB.JsonIgnore]
    public bool IsLimit
    {
        get
        {
            if (peoples.Count > 2) //限速條件,自己定義
            {
                return true;
            }
            return false;
        }
    }
}

RateLimitAttribute

作用:標籤打在介面方法上,並設定併發數量

namespace Utils
{
    /// <summary>
    /// 介面限速
    /// </summary>
    public class RateLimitAttribute : Attribute
    {
        private Semaphore _sem;

        public Semaphore Sem
        {
            get
            {
                return _sem;
            }
        }

        public RateLimitAttribute(int limitCount = 1)
        {
            _sem = new Semaphore(limitCount, limitCount);
        }
    }
}

使用RateLimitAttribute

標籤打在介面方法上,並設定併發數量。
伺服器好像是24核的,併發限制為8應該沒問題。

[HttpPost]
[Route("[action]")]
[RateLimit(8)]
public async Task<List<XxxInfo>> Query([FromBody] XxxPostData data)
{
    ...省略
}

限制介面併發量的攔截器RateLimitFilter

/// <summary>
/// 介面限速
/// </summary>
public class RateLimitFilter : ActionFilterAttribute
{
    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        Type controllerType = context.Controller.GetType();
        object arg = context.ActionArguments.Values.ToList()[0];
        var rateLimit = context.ActionDescriptor.EndpointMetadata.OfType<RateLimitAttribute>().FirstOrDefault();

        bool isLimit = false; //是否限速
        if (rateLimit != null && arg is RateLimitInterface) //介面方法打了RateLimitAttribute標籤並且引數實體類實現了RateLimitInterface介面時才限速,否則不限速
        {
            RateLimitInterface model = arg as RateLimitInterface;
            if (model.IsLimit) //滿足限速條件
            {
                isLimit = true;
                Semaphore sem = rateLimit.Sem;

                if (sem.WaitOne(0))
                {
                    try
                    {
                        await next.Invoke();
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        sem.Release();
                    }
                }
                else
                {
                    var routeList = context.RouteData.Values.Values.ToList();
                    routeList.Reverse();
                    var route = string.Join('/', routeList.ConvertAll(a => a.ToString()));
                    var msg = $"當前訪問{route}介面的使用者數太多,請稍後再試";
                    LogUtil.Info(msg);
                    context.Result = new ObjectResult(new ApiResult
                    {
                        code = (int)HttpStatusCode.BadRequest,
                        message = msg
                    });
                }
            }
        }

        if (!isLimit)
        {
            await next.Invoke();
        }
    }
}

註冊攔截器

//攔截器
builder.Services.AddMvc(options =>
{
    ...省略

    options.Filters.Add<RateLimitFilter>();
});

使用jMeter進行壓力測試

測試結果:

  1. 被限速的介面,滿足限速條件的呼叫併發量大時,部分使用者成功,部分使用者提示當前查詢的人多請稍後再試。但不影響未滿足限速條件的傳參呼叫,也不影響其它未限速介面的呼叫。
  2. 測試的所有介面、所有查詢引數條件的呼叫,耗時穩定,大量併發時,不會出現介面耗時幾十秒甚至1分鐘的情況。

相關文章