node.js请求超时

时间:2015-12-02 12:50:50

标签: linux node.js request

我想知道node.js request模块如何处理timeout参数。

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) 这是否意味着timeout中的request选项最多为20秒(如果我不更改Linux Kernel timeout),无论我在options中设置了什么? 我使用Ubuntu

3 个答案:

答案 0 :(得分:2)

从请求包的自述文件:

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

答案 1 :(得分:2)

request返回错误,错误代码设置如request自述文件(超时部分)中所述。

查看TIME_WAIT详细信息。

但是,是的,内核将通过其配置将其削减。如您的链接所述,您可以通过查看tcp_syn_retries来更改它。

答案 2 :(得分:0)

如果发生超时,将执行回调函数,并将错误设置为消息'错误:ETIMEDOUT'。

这个小项目https://github.com/FGRibreau/node-request-retry提供了现成的,配置好的包装器,用于通过许多连接错误代码触发重试,包括超时。

相关问题