假设我有一个消息队列,它的生产时间会长得多
var mq = ["A","B","C"];
我想通过UDP发送每条消息但是我需要对它进行速率限制,以免压倒接收器。
while(mq.length)
{
limit.removeTokens(1,function(){
var m = mq.pop();
client.send(m,0,m.length,port,ip, function(err,bytes){
console.log("sent");
});
});
}
据我了解,while循环将阻塞,并且实际上不会发送数据。它实际上最终导致内存分配错误,因为它一直在旋转。
我尝试使用process.nextTick()但最终会出现递归错误。
解决这个问题的正确方法是什么?
谢谢!
答案 0 :(得分:0)
这可以使用简单的队列建模。这是一个例子:
var mq = ["A","B","C"];
// create a queue with the max concurrent jobs to run
// and a function that starts a new job
var queue = new Queue(5, function(item, callback){
client.send(item, 0, item.length, ip, function(){
// signal that we're done, and another item can start
callback();
});
});
// add an array of items to the queue
mq.forEach(queue.add);
function Queue(max, handler){
var queueItems = [];
// we keep a count of the number of unused job slots we have
// when this is more than 0, a new job will start
this.available = max;
this.add = function(item){
queueItems.push(item);
process.nextTick(function(){
this.maybeRunActions();
}.bind(this));
}.bind(this);
// this will run actions if both:
// - we have actions to run
// - we have unused slots
this.maybeRunActions = function(){
while (this.available > 0 && queueItems.length > 0) {
this.available -= 1;
// call the handler passed to new Queue, which kicks of the job
// and tells the queue when the job is complete
handler(queueItems.shift(), function(){
this.available += 1;
this.maybeRunActions();
}.bind(this));
}
}
}