简体   繁体   English

NodeJs:在maxsockets限制为10的情况下,如何限制globalAgent中的请求队列

[英]NodeJs: In Case when maxsockets are limited to 10, how to limit request queue in globalAgent

There is a node server hosted and from application we also make a request to some external api over http. 有一个节点服务器托管,从应用程序我们也通过http向一些外部api发出请求。 This external service can process 10request/sec. 此外部服务可以处理10request / sec。 Application is behind Nginx which has timeout 30 secs. 应用程序支持Nginx,超时30秒。 Now let say we put load of 10k request on nodejs app server. 现在假设我们在nodejs app服务器上加载10k请求。 Since we do have dependency on external api which can process max 10*30 request in 30 secs. 因为我们确实依赖于外部api,它可以在30秒内处理最大10 * 30请求。 Only 300 request will be served and remaining will be terminated by Nginx. 只有300个请求将被提供,其余的将由Nginx终止。 But still this 10k request got queued into https.globalAgent.requests queue and keep running. 但是这个10k的请求仍然排队进入https.globalAgent.requests队列并继续运行。 There is no way to specify sockettimeout or limit the size of the request queue. 无法指定sockettimeout或限制请求队列的大小。 Further call to application will eventually be queued up for external service and later will be terminated by Nginx. 对应用程序的进一步调用最终将排队等待外部服务,之后将由Nginx终止。

So questions are : Is there any way we can set socketTimeOut? 所以问题是:我们有什么办法可以设置socketTimeOut吗? Is there any way we can limit the size of the queue?. 有什么办法可以限制队列的大小吗? Any workaround ? 任何解决方法?

Sample Code 示例代码

var http = require('http');
var https = require('https');
var Q = require('q');
var file = require('fs');
var request = require('request');
http.globalAgent.maxSockets = 10;
https.globalAgent.maxSockets = 10;
https.globalAgent.keepAlive=true;


http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});

    var st = new Date();
    var rr = request(
        {url:'https://amazon.com',timeout:100000,time:true},
        function(err,resp,body){
            var et = new Date();
            // console.log( resp && resp.timings.socket,st-et,err);
            console.log(https.globalAgent)
            res.end('ok');
        }
    );


}).listen(9898);

I'll suggest you to use a rate limiting library like https://github.com/jhurliman/node-rate-limiter 我建议你使用像https://github.com/jhurliman/node-rate-limiter这样的速率限制库

In case of an exceded limit, you can answer immediately to the requests, with a 429 error code ( https://httpstatuses.com/429 ) or a ko error message or you can wait until you have an available request slot 如果超出限制,您可以立即回复请求,并提供429错误代码( https://httpstatuses.com/429 )或错误消息,或者您可以等到有可用的请求插槽

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM