Node.JS:处理每分钟最大请求到服务器的最佳方式 [英] Node.JS: Best way to handle max requests per minute to a server

查看:25
本文介绍了Node.JS:处理每分钟最大请求到服务器的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这个问题已经得到回答,我很抱歉,我希望我没有违反任何 SO 规则,如果是这样,我提前道歉......我想知道处理请求限制器的最佳方法是什么?我在网上看到了一堆节流阀和速率限制器,但我不确定它如何或是否适用于我的情况.

I'm sorry if this question as already been answered and I hope I'm not breaking any SO rule, if so, in advance I apologise... I was wondering what was the best way to handle a request limiter? I've seen a bunch of throttles and rate-limiters online but I'm not sure how or if it could apply in my case.

我正在做一堆基于数组的 [OUTGOING] 请求承诺,而在服务器上我每分钟只能发出 90 个请求.我的请求承诺是由这个命令生成的:return Promise.all(array.map(request)).

I'm doing a bunch of [OUTGOING] request-promises based on an Array and on a server I can only make 90 request per minute. My request-promises are generated by this command: return Promise.all(array.map(request)).

我想这样处理它:

var i = 0;

return rp({
        url: uri,
        json: true,
      }).then((data) => {
        if (i <=90) {
          i ++;
          return data;
        } else {
          return i;
        }
      });

但我不确定这是否是一种真正有效的处理方式,另外,我不确定如何处理时间关系......:S

but I'm not sure if it will be a really effective way to handle it plus, I'm not sure how to handle the time relation yet... :S

在此先感谢您的帮助,对不起,我仍然是一个巨大的初学者......

Thanks in advance for your help and sorry I'm still a huge beginner...

推荐答案

如果请求是从不同的代码部分开始的,那么实现类似于 服务器队列 的东西可能会很有用,它等待请求直到允许这样做.一般处理程序:

If the requests are started from different code parts, it might be useful to implement sth like a server queue which awaits the request until it is allowed to do so. The general handler:

var fromUrl = new Map();

function Server(url, maxPerMinute){
 if(fromUrl.has(url)) return fromUrl.get(url);
 fromUrl.set(url,this);

  this.tld = url;
  this.maxPerMinute = maxPerMinute;
  this.queue = [];
  this.running = false;

}


  Server.prototype ={
   run(d){
    if(this.running && !d) return;
    var curr = this.queue.shift();
    if(!curr){
      this.running = false;
      return;
    }
   var [url,resolve] = curr;
   Promise.all([
     request(this.tld + url),
     new Promise(res => setTimeout(res, 1000*60/this.maxPerMinute)
    ]).then(([res]) => {
       resolve(res);
       this.run(true);
    });
  },
  request(url){
   return new Promise(res => {
      this.queue.push([url,res]);
      this.run();
    });
  }
};

module.exports = Server;

可以这样使用:

 var google = new require("server")("http://google.com");

google.maxPerMinute = 90;

google.request("/api/v3/hidden/service").then(res => ...);

这篇关于Node.JS:处理每分钟最大请求到服务器的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆