Node.js限制API请求并将队列限制为1

问题描述

所需功能

我有一个节点服务器,当客户端请求重新加载数据时,该服务器从第三方API请求数据。我想限制我的节点服务器每5分钟最多请求一次重新加载数据的次数,无论哪个用户请求重新加载数据。

问题

此刻我正在使用节流队列,但是我想将队列限制为1。如果在队列已经为1的情况下提出了任何其他请求,那么我希望该请求被忽略。

>

代码

const throttledQueue = require("throttled-queue");
const throttle = throttledQueue(1,1500);
router.get("/throttle",async (req,res,next) => {
  try {
    throttle(async function () {
      const response = await http.get();
      console.log("response in throttle test route",response.data);
      res.status(200).send({ response: response.data });
    });
  } catch (error) {
    console.log("error",error);
  }
});

如何实现?此外,即使其他用户发出请求,节流队列仍然每5分钟仅调用一次我的外部API调用吗?

解决方法

我认为节气门是您在此处使用的错误概念。确实,您想使用5分钟过期时间的缓存。您可以为此或各种缓存库中的任何一个使用节点缓存。如果发生高速缓存未命中,您将调用加载数据并重新填充高速缓存。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...