限制ASP.NET Web API同时处理的请求数量

5
我正在使用ASP.NET Web API 2.2和Owin构建Web服务,我观察到每个控制器的调用将由在服务器端运行的单独线程提供服务,这并不令人惊讶,也是我预期的行为。
现在我遇到的一个问题是,因为服务器端操作对内存的需求很高,所以如果同时有超过X个用户调用,服务器代码很可能会抛出内存不足异常。
是否可以设置全局“最大操作计数”,以便Web Api可以排队(而不是拒绝)传入的呼叫,并且只在有空闲插槽时才继续进行。
我无法以64位运行Web服务,因为一些引用的库不支持64位。
我还查看了像https://github.com/stefanprodan/WebApiThrottle这样的库,但它只能基于调用频率进行节流。
谢谢
1个回答

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);
        }
    }
}

谢谢,正确的方式是如何在Owin管道中正确放置OwinMiddleware?我尝试在StartUp中使用app.use<MaxConccurrentMiddleware>,但并发检查仅在请求完成后才触发,因此响应具有所有正常内容,但响应代码设置为429。 - Godsent
啊..我想我现在明白了...我忘记在maxConcurrentRequests被违反的情况下返回,所以它总是调用管道中的下一个活动。 - Godsent
429还是503?当请求来自同一来源时,太多请求的429状态码是相关的,我认为503服务不可用适合这种情况。 :P - Nameless
app.Use<MaxConcurrentMiddleware>(Convert.ToInt32(ConfigurationManager.AppSettings["ConcurrentRequests"])); - JumpingJezza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接