ToB企服应用市场:ToB评测及商务社交产业平台

标题: ASP.NET Core Web API 接口限流 [打印本页]

作者: 数据人与超自然意识    时间: 2023-3-9 21:41
标题: ASP.NET Core Web API 接口限流
前言

ASP.NET Core Web API 接口限流、限制接口并发数量,我也不知道自己写的有没有问题,抛砖引玉、欢迎来喷!
需求

说明

效果截图

下面是使用jMeter并发测试时,打的接口日志:

代码

RateLimitInterface

接口参数的实体类要继承该接口
  1. using JsonA = Newtonsoft.Json;
  2. using JsonB = System.Text.Json.Serialization;
  3. namespace Utils
  4. {
  5.     /// <summary>
  6.     /// 限速接口
  7.     /// </summary>
  8.     public interface RateLimitInterface
  9.     {
  10.         /// <summary>
  11.         /// 是否限速
  12.         /// </summary>
  13.         [JsonA.JsonIgnore]
  14.         [JsonB.JsonIgnore]
  15.         bool IsLimit { get; }
  16.     }
  17. }
复制代码
接口参数实体类

继承RateLimitInterface接口,并实现IsLimit属性
  1. public class XxxPostData : RateLimitInterface
  2. {
  3.     ...省略
  4.     /// <summary>
  5.     /// 是否限速
  6.     /// </summary>
  7.     [JsonA.JsonIgnore]
  8.     [JsonB.JsonIgnore]
  9.     public bool IsLimit
  10.     {
  11.         get
  12.         {
  13.             if (peoples.Count > 2) //限速条件,自己定义
  14.             {
  15.                 return true;
  16.             }
  17.             return false;
  18.         }
  19.     }
  20. }
复制代码
RateLimitAttribute

作用:标签打在接口方法上,并设置并发数量
  1. namespace Utils
  2. {
  3.     /// <summary>
  4.     /// 接口限速
  5.     /// </summary>
  6.     public class RateLimitAttribute : Attribute
  7.     {
  8.         private Semaphore _sem;
  9.         public Semaphore Sem
  10.         {
  11.             get
  12.             {
  13.                 return _sem;
  14.             }
  15.         }
  16.         public RateLimitAttribute(int limitCount = 1)
  17.         {
  18.             _sem = new Semaphore(limitCount, limitCount);
  19.         }
  20.     }
  21. }
复制代码
使用RateLimitAttribute

标签打在接口方法上,并设置并发数量。
服务器好像是24核的,并发限制为8应该没问题。
  1. [HttpPost]
  2. [Route("[action]")]
  3. [RateLimit(8)]
  4. public async Task<List<XxxInfo>> Query([FromBody] XxxPostData data)
  5. {
  6.     ...省略
  7. }
复制代码
限制接口并发量的拦截器RateLimitFilter
  1. /// <summary>
  2. /// 接口限速
  3. /// </summary>
  4. public class RateLimitFilter : ActionFilterAttribute
  5. {
  6.     public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  7.     {
  8.         Type controllerType = context.Controller.GetType();
  9.         object arg = context.ActionArguments.Values.ToList()[0];
  10.         var rateLimit = context.ActionDescriptor.EndpointMetadata.OfType<RateLimitAttribute>().FirstOrDefault();
  11.         bool isLimit = false; //是否限速
  12.         if (rateLimit != null && arg is RateLimitInterface) //接口方法打了RateLimitAttribute标签并且参数实体类实现了RateLimitInterface接口时才限速,否则不限速
  13.         {
  14.             RateLimitInterface model = arg as RateLimitInterface;
  15.             if (model.IsLimit) //满足限速条件
  16.             {
  17.                 isLimit = true;
  18.                 Semaphore sem = rateLimit.Sem;
  19.                 if (sem.WaitOne(0))
  20.                 {
  21.                     try
  22.                     {
  23.                         await next.Invoke();
  24.                     }
  25.                     catch
  26.                     {
  27.                         throw;
  28.                     }
  29.                     finally
  30.                     {
  31.                         sem.Release();
  32.                     }
  33.                 }
  34.                 else
  35.                 {
  36.                     var routeList = context.RouteData.Values.Values.ToList();
  37.                     routeList.Reverse();
  38.                     var route = string.Join('/', routeList.ConvertAll(a => a.ToString()));
  39.                     var msg = $"当前访问{route}接口的用户数太多,请稍后再试";
  40.                     LogUtil.Info(msg);
  41.                     context.Result = new ObjectResult(new ApiResult
  42.                     {
  43.                         code = (int)HttpStatusCode.BadRequest,
  44.                         message = msg
  45.                     });
  46.                 }
  47.             }
  48.         }
  49.         if (!isLimit)
  50.         {
  51.             await next.Invoke();
  52.         }
  53.     }
  54. }
复制代码
注册拦截器
  1. //拦截器
  2. builder.Services.AddMvc(options =>
  3. {
  4.     ...省略
  5.     options.Filters.Add<RateLimitFilter>();
  6. });
复制代码
使用jMeter进行压力测试

测试结果:

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4