简体   繁体   English

Node.js - 如何节流和限制逻辑但不限制主端点?

[英]Node.js - How to throttle and limit logic but not limiting main endpoint?

The question might sound a little weird but I am not sure how to handle this specific issue.这个问题可能听起来有点奇怪,但我不确定如何处理这个具体问题。

I have a requests than does a few things and sends a response back to the client.我有一个请求而不是做一些事情并将响应发送回客户端。 In this specific requests i am also doing something after the response is sent back to do some backround stuff.在这个特定的请求中,我也在将响应发送回做一些后台工作后做一些事情。 The issue is lying inside this piece of logic / functionality since it requests a third party public API that has a rate limit.问题在于这部分逻辑/功能,因为它请求具有速率限制的第三方公共 API。 Let's say i send 20 requests/s to this endpoint.假设我向该端点发送 20 个请求/秒。

10 requests will be processed by the third party public API and processed correctly, but the last 10 requests will not be processed and will return a rate limit error. 10个请求会被第三方public API处理并正确处理,但最后10个请求不会被处理,会返回限速错误。

My question is - How can I change this logic / endpoint to support my demands.我的问题是 - 我怎样才能改变这个逻辑/端点来支持我的需求。 Any feedback and suggestions is much appreciated.非常感谢任何反馈和建议。

// endpoint /get-data/
await doAlotOfLogicHere();

setTimeout(() => {
      // Do something after 1 seconds
      // This specific action can only take 10 requests / second
      controller.doSomething(req,res)
    }, 1000);

// Send response to client
res.status(200).send(data);

controller.doSomething() controller.doSomething()

exports.doSomething = (req,res) => {
await sendDataToPublicAPI();
}

Your problem is a little big vague... Let me suggest something, though.你的问题有点模糊......不过,让我提出一些建议。

  1. Push the user request to a queue (this would be a database table with the resource, payload and timestamp)将用户请求推送到队列(这将是一个包含资源、有效负载和时间戳的数据库表)
  2. Fire it from a schedule or enter link description here计划中触发它或在此处输入链接描述
  3. Make little asynchronous request to check whether the response is avaiable发出少量异步请求以检查响应是否可用
  4. Fetch the result data.获取结果数据。 It's best if you can cache it in your own database最好能缓存在自己的数据库中

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

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