【问题标题】:How to limit the amount of async calls in node js?如何限制节点 js 中的异步调用数量?
【发布时间】:2019-09-14 01:51:47
【问题描述】:

我正在尝试将我可以对服务器进行的异步调用数量限制为每秒 1 个调用。我查看了 async eachOfLimit,但不确定这是否是正确的解决方案。

我正在寻找一个已经存在的库,它将包裹请求模块并实际上将请求限制为每秒 1 个。我只是不知道如何处理这种情况,我希望有某种标准。

【问题讨论】:

标签: node.js asynchronous throttling


【解决方案1】:

如果你使用express,你可以使用来自 npm 的 express-rate-limit 包。下面的用法-

const rateLimit = require("express-rate-limit");


app.enable("trust proxy"); // only if you're behind a reverse proxy (Heroku, Bluemix, AWS ELB, Nginx, etc)

const limiter = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 1 // limit each IP to 1 requests per windowMs
});

//  apply to all requests
app.use(limiter);

【讨论】:

  • 感谢您的解决方案,如何将其添加到包含异步函数的类中?
  • 你能再澄清一下你的用例吗?此模块将允许您定义端点的速率限制。您的客户端将只能根据您定义的限制调用 API。从客户端,您只需向您的服务器发出正常的fetch 调用。
猜你喜欢
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 2017-01-09
  • 2016-12-26
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多