簡體   English   中英

NodeJs:在maxsockets限制為10的情況下,如何限制globalAgent中的請求隊列

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

有一個節點服務器托管,從應用程序我們也通過http向一些外部api發出請求。 此外部服務可以處理10request / sec。 應用程序支持Nginx,超時30秒。 現在假設我們在nodejs app服務器上加載10k請求。 因為我們確實依賴於外部api,它可以在30秒內處理最大10 * 30請求。 只有300個請求將被提供,其余的將由Nginx終止。 但是這個10k的請求仍然排隊進入https.globalAgent.requests隊列並繼續運行。 無法指定sockettimeout或限制請求隊列的大小。 對應用程序的進一步調用最終將排隊等待外部服務,之后將由Nginx終止。

所以問題是:我們有什么辦法可以設置socketTimeOut嗎? 有什么辦法可以限制隊列的大小嗎? 任何解決方法?

示例代碼

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

我建議你使用像https://github.com/jhurliman/node-rate-limiter這樣的速率限制庫

如果超出限制,您可以立即回復請求,並提供429錯誤代碼( https://httpstatuses.com/429 )或錯誤消息,或者您可以等到有可用的請求插槽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM