【问题标题】:TCP session reuse in SuperagentSuperagent 中的 TCP 会话重用
【发布时间】:2020-11-29 22:16:53
【问题描述】:

我正在使用superagent,在检查网络时我注意到 superagent 正在为每个请求创建一个新的 TCP 连接。我正在使用 superagent 处理一系列请求,这会导致大量 TCP 连接(可能达到数百个)。

我尝试关注this idea 并使用agentkeepalive 包,但是这种方法有一些缺点:

  1. 虽然 superagent 可以开箱即用地使用 http 和 https,但 agentkeepalive 需要根据协议进行定义。
  2. 作为上一节的结果,如果我执行重定向到 https 请求的 http 请求,我会收到 Protocol "https:" not supported. Expected "http:" 错误,因为协议已更改。
  3. 由于第 2 节,应用程序崩溃了,因为 uncaughtException (仅在重定向时发生,而不是在使用错误协议时发生,即 http agentkeepalive 用于 https 请求)

不用说,使用request.set('Connection', 'keep-alive'); 并没有解决它。

所以我的问题是:如何在使用superagent 时重用 TCP 连接而不会出现重定向错误?除了agentkeepalive 包之外,还有没有其他解决方案可以重用superagent 中的TCP 连接?

【问题讨论】:

    标签: tcp keep-alive superagent


    【解决方案1】:

    使用这个库:https://www.npmjs.com/package/agentkeepalive 您可以像这样将它与 superagent 集成:

    const request = require('superagent');
    const Agent = require('agentkeepalive');
    
    const keepaliveAgent = new Agent({
      maxFreeSockets: 50,
    });
    
    request.get('http//www.example.com/path')
           .agent(keepaliveAgent);
    

    在此示例中,最大连接数是无限的,但它会保持最多 50 个空闲连接打开,默认保持活动超时设置(30 秒)

    编辑:

    关于使用 agentkeepalive 的 http 和 https 协议,我在我的案例中所做的是以下解决方法:

    this.agent = new (baseUrl.toLowerCase().startsWith('https:')
                ? Agent.HttpsAgent
                : Agent)(
                {
                    maxFreeSockets: 50,
                    timeout: 60000,
                    freeSocketTimeout: 30000,
                },
            );
    

    假设 baseUrl 将始终与此代理一起使用。虽然它可能不是开箱即用的协议,但它是一个非常简单的解决方案,我将它用作我所有 REST 客户端的基类

    【讨论】:

    • 嗨,正如我的问题中所述 - 我尝试使用 agentkeepalive 但它不适合
    • 对不起,你是对的。我刚刚使用解决您指出的问题的解决方法编辑了答案
    猜你喜欢
    • 1970-01-01
    • 2011-12-19
    • 2014-01-13
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 1970-01-01
    • 2012-05-20
    相关资源
    最近更新 更多