【问题标题】:How do I manage a large number of HTTP requests in node如何管理节点中的大量 HTTP 请求
【发布时间】:2018-04-15 12:52:10
【问题描述】:

一直在网上寻找答案,但没有找到任何结论。

我有一个节点应用程序(可能)需要发出大量 HTTP GET 请求。

假设http://foo.com/bar 允许一个“id”查询参数,并且我有大量的 ID 需要处理(~1k),即
http://foo.com/bar?id=100
http://foo.com/bar?id=101
等等

人们使用过的哪些库可能最适合这项任务?

我想我正在寻找队列和连接池之间的东西:

  1. 设置:

    • 存在要处理的大量 ID(最多约 1k 个 ID)
  2. 流程:

    • 定义了某种包含X“工人”数量的池
    • 每个工作人员获取一个 ID 并发出请求(一次最多运行 X 个并发工作人员)
    • 当工作人员完成时,它会从数组中获取下一个 ID 并处理它
    • 等。直到处理完所有 ID

欢迎任何经验

【问题讨论】:

    标签: node.js performance http concurrency


    【解决方案1】:

    它实际上比我最初想象的要简单得多,并且只需要 Bluebird(我在这里稍微解释一下,因为我的最终代码最终要复杂得多):

    var Promise = require('bluebird');
    ...
    var allResults = [];
    ...
    Promise.map(idList, (id) => {
          // For each ID in idList, make a HTTP call
          return http.get( ... url: 'http://foo.com/bar?id=' + id ... )
                  .then((httpResposne) => {
                    return allResults.push(httpResposne);
                  })
                  .catch((err) => {
                    var errMsg = 'ERROR: [' + err + ']';
                    console.log(errMsg + (err.stack ? '\n' + err.stack : ''));
    
                  });
        }, { concurrency: 10 }) // Max of 10 concurrent HTTP calls at once
        .then(() => {
          // All requests are now complete, return all results
          return res.json(allResults);
        });
    

    【讨论】:

      猜你喜欢
      • 2014-08-23
      • 1970-01-01
      • 2012-04-27
      • 2015-02-18
      • 2016-01-11
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多