【问题标题】:Node.js Calling functions as quickly as possible without going over some limitNode.js 尽可能快地调用函数而不超出某些限制
【发布时间】:2018-03-02 03:30:38
【问题描述】:

我有多个调用不同 api 端点的函数,我需要尽可能快地调用它们,而不超出某些限制(例如每秒 20 次调用)。对于我给出的示例,我当前的解决方案是延迟并每 50 毫秒调用一次函数,但我想尽快调用它们,而不仅仅是将调用与速率限制相等。

【问题讨论】:

  • 查看“漏桶”算法和相关的 NPM 包来帮助你使用它。
  • 你需要节流或去抖动

标签: node.js api throttling rate-limiting


【解决方案1】:

function-rate-limit 为我解决了类似的问题。 function-rate-limit 随着时间的推移分散对您的函数的调用,而不会丢弃对您的函数的调用。在达到速率限制之前,它仍然允许对您进行即时调用,因此它可以在正常情况下不引入延迟。

function-rate-limit 文档中的示例:

var rateLimit = require('function-rate-limit');

// limit to 2 executions per 1000ms 
var start = Date.now()
var fn = rateLimit(2, 1000, function (x) {
  console.log('%s ms - %s', Date.now() - start, x);
});

for (var y = 0; y < 10; y++) {
  fn(y);
}

结果:

10 ms - 0
11 ms - 1
1004 ms - 2
1012 ms - 3
2008 ms - 4
2013 ms - 5
3010 ms - 6
3014 ms - 7
4017 ms - 8
4017 ms - 9

【讨论】:

    【解决方案2】:

    您可以尝试使用来自async 的队列。执行此操作时要小心,它的行为本质上类似于其他语言中的 while(true)

    const async = require('async');
    
    const concurrent = 10; // At most 10 concurrent ops;
    const tasks = Array(concurrent).fill().map((e, i) => i);
    
    let pushBack; // let's create a ref to a lambda function
    
    const myAsyncFunction = (task) => {
      // TODO: Swap with the actual implementation
      return Promise.resolve(task);
    };
    
    const q = async.queue((task, cb) => {
      myAsyncFunction(task)
        .then((result) => {
          pushBack(task);
          cb(null, result);
        })
        .catch((err) => cb(err, null));
    }, tasks.length);
    
    pushBack = (task) => q.push(task);
    q.push(tasks);
    

    这里发生了什么?我们说“嘿,并行运行 X 个任务”,每个任务完成后,我们将其放回队列中,这相当于说“永远并行运行 X 个任务”

    【讨论】:

      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2012-11-19
      • 1970-01-01
      • 2013-06-28
      • 1970-01-01
      相关资源
      最近更新 更多