限制 ASP.NET Web API 服务的并发请求

God*_*ent 5 asp.net asp.net-web-api asp.net-web-api2

我使用 ASP.NET Web API 2.2 和 Owin 来构建 Web 服务,并且我观察到对控制器的每次调用都将由在服务器端运行的单独线程提供服务,这并不奇怪,也是我所期望的行为。

我现在遇到的一个问题是,因为服务器端操作非常占用内存,所以如果有超过 X 个用户同时调用,服务器代码很可能会抛出内存不足异常。

是否可以设置全局“最大操作计数”,以便 Web Api 可以对传入呼叫进行排队(而不是拒绝),并且仅在有空槽时才继续。

我无法在 64 位中运行 Web 服务,因为某些引用的库不支持该功能。

我还查看了像https://github.com/stefanprodan/WebApiThrottle这样的库,但它只能根据调用频率进行限制。

谢谢

Tre*_*ley 5

您可以按照以下方式添加一段内容OwinMiddleware(受您链接到的 WebApiThrottle 的影响):

public class MaxConccurrentMiddleware : OwinMiddleware
{
    private readonly int maxConcurrentRequests;
    private int currentRequestCount;

    public MaxConccurrentMiddleware(int maxConcurrentRequests)
    {
        this.maxConcurrentRequests = maxConcurrentRequests;
    }

    public override async Task Invoke(IOwinContext context)
    {
        try
        {
            if (Interlocked.Increment(ref currentRequestCount) > maxConcurrentRequests)
            {
                var response = context.Response;

                response.OnSendingHeaders(state =>
                {
                    var resp = (OwinResponse)state;
                    resp.StatusCode = 429; // 429 Too Many Requests
                }, response);

                return Task.FromResult(0);
            }

            await Next.Invoke(context);
        }
        finally
        {
            Interlocked.Decrement(ref currentRequestCount);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)