簡體   English   中英

node.js請求中的超時

[英]Timeout in node.js request

我想知道關於timeout參數, node.js request模塊如何工作。

timeout時間過后會發生什么? 即:

var request = require('request');
var options = {
    url: Theurl,
    timeout: 300000
};

request(options, function(error, resp, body) {...

300000之后會怎樣? 請求是否嘗試再次請求URL?

我還發現Linux Kernel具有默認的20秒TCP socket connection timeout. http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout )是否意味着request中的timeout選項最多為20秒(如果我不更改Linux Kernel timeout ),無論我在options設置了什么? 我使用Ubuntu

從請求包的自述文件中:

Note that if the underlying TCP connection cannot be established, 
the OS-wide TCP connection timeout will overrule the timeout option

因此,根據您的情況,該請求將在20秒后中止。 該請求不會嘗試再次請求該url(即使超時設置為小於20000的值)。 您將為此編寫自己的邏輯或使用其他包,例如requestretry

例:

var options = {
    url: 'http://www.gooooerererere.com/',
    timeout: 5000
}

var maxRequests = 5;

function requestWithTimeout(attempt){
    request(options, function(error,response,body){
        if(error){
            console.log(error);

            if(attempt==maxRequests)
                return;
            else
                requestWithTimeout(attempt+1);
        }
        else {
            //do something with result
        }
    });
}

requestWithTimeout(1);

您還可以使用以下命令檢查特定的錯誤消息,例如ETIMEDOUT

if(error.code == [ERROR_MESSAGE])

request返回錯誤,並按照請求自述文件(超時部分)中所述設置錯誤代碼。

查看TIME_WAIT詳細信息。

但是,是的,內核將通過其配置來減少它。 如您的鏈接所述,您可以通過更改tcp_syn_retries進行更改。

如果發生超時,您的回調函數將被執行,錯誤設置為消息“錯誤:ETIMEDOUT”。

這個小項目https://github.com/FGRibreau/node-request-retry提供了現成的,配置好的包裝器,用於使由許多連接錯誤代碼(包括超時)觸發的重試。

暫無
暫無

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

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