简体   繁体   English

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

[英]Node.js throttle API requests and limit queue to 1

Desired Functionality所需的功能

I have a node server that requests data from a third party API when the client requests data to be reloaded.我有一个节点服务器,当客户端请求重新加载数据时,它会从第三方 API 请求数据。 I want to throttle the amount of times my node server requests reloaded data to a maximum of once every 5 minutes, regardless of which user requests the data to be reloaded.我想将节点服务器请求重新加载数据的次数限制为最多每 5 分钟一次,无论哪个用户请求重新加载数据。

Problem问题

I'm using throttled-queue at the moment, however I want to limit the queue to 1. If any additional requests are made when there is already a queue of 1, then I want that request to be disregarded.我目前正在使用节流队列,但是我想将队列限制为 1。如果在队列为 1 时发出任何其他请求,那么我希望该请求被忽略。

Code代码

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);
  }
});

How can I achieve this?我怎样才能做到这一点? Also, will throttle-queue still only call my external API call once every 5 minutes even if different users make requests?另外,即使不同的用户发出请求,油门队列仍然每 5 分钟只调用一次我的外部 API 调用吗?

I think throttle is the wrong concept for you to be using here.我认为油门是你在这里使用的错误概念。 Really, you want to be using a cache with a 5 minute expiration time.确实,您希望使用具有 5 分钟到期时间的缓存。 You could use node-cache for this or any one of the various cache libraries.您可以为此使用节点缓存或各种缓存库中的任何一个。 On cache miss you make the call to load the data and repopulate the cache.在缓存未命中时,您会调用加载数据并重新填充缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM