ASP.NET Core Web API 介面限流、限制介面並行數量,我也不知道自己寫的有沒有問題,拋磚引玉、歡迎來噴!
下面是使用jMeter並行測試時,打的介面紀錄檔:
介面引數的實體類要繼承該介面
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;
}
}
}
作用:標籤打在介面方法上,並設定並行數量
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);
}
}
}
標籤打在介面方法上,並設定並行數量。
伺服器好像是24核的,並行限制為8應該沒問題。
[HttpPost]
[Route("[action]")]
[RateLimit(8)]
public async Task<List<XxxInfo>> Query([FromBody] XxxPostData data)
{
...省略
}
/// <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>();
});
測試結果: