前言
ASP.NET Core Web API 接口限流、限制接口併發數量,我也不知道自己寫的有沒有問題,拋磚引玉、歡迎來噴!
需求
- 寫了一個接口,參數可以傳多個人員,也可以傳單個人員,時間範圍限制最長一個月。簡單來說,當傳單個人員時,接口耗時很短,當傳多個人員時,一般人員會較多,接口耗時較長,一般耗時幾秒。
- 當傳多個人員時,併發量高時,接口的耗時就很長了,比如100個用戶併發請求,耗時可長達幾十秒,甚至1分鐘。
- 所以需求是,當傳單個人員時,不限制。當傳多個人員時,限制併發數量。如果併發用戶數少於限制數,那麼所有用戶都能成功。如果併發用戶數,超出限制數,那麼超出的用戶請求失敗,並提示"當前進行XXX查詢的用戶太多,請稍後再試"。
- 這樣也可以減輕被請求的ES集羣的壓力。
說明
- 使用的是.NET6
- 我知道有人寫好了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)) //注意:超時時間爲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.ServiceUnavailable,
message = "當前查詢的用戶太多,請稍後再試。"
});
}
}
}
if (!isLimit)
{
await next.Invoke();
}
}
}
上述代碼說明:sem.WaitOne(0)這個超時時間,最好是0,即不等待,否則高併發下會有問題。SemaphoreSlim的異步wait沒試過。如果超時時間大於0,意味着,高併發下,會有大量的等待,異步等待也是等待。
SemaphoreSlim短時間是自旋,想象一下一瞬間產生大量自旋會怎麼樣?所以最好不等待,如果要等待,那代碼還得再研究研究,經過測試才能用。
註冊攔截器
//攔截器
builder.Services.AddMvc(options =>
{
...省略
options.Filters.Add<RateLimitFilter>();
});
使用jMeter進行壓力測試
測試結果:
- 被限速的接口,滿足限速條件的調用併發量大時,部分用戶成功,部分用戶提示當前查詢的人多請稍後再試。但不影響未滿足限速條件的傳參調用,也不影響其它未限速接口的調用。
- 測試的所有接口、所有查詢參數條件的調用,耗時穩定,大量併發時,不會出現接口耗時幾十秒甚至1分鐘的情況。