我使用RabbitMQ,我需要在队列中获取随机数量的消息。
但是,不幸的是,运行代码时,预取和Qos设置不起作用。 2条消息同时具有相同的diliveryTag。 因此我无法获得预期的消息数量。
这是我的代码:
exports.getMessageFromQueue = async function(queue,numbMessage) {
var exchange = queue + '.exchange';
var result = [];
var countReceive = 0;
var isDone = false;
let channel = await conn.createChannel()
let response = await channel.assertQueue(queue)
await channel.prefetch(1);
await channel.qos(1);
response = await channel.bindQueue(response.queue, exchange, '');
channel.consume(response.queue,getMessage(numbMessage), {noAck: false})
setTimeout(() => {
eventEmitter.emit('consumeDone');
if(channel != null)channel.close();}, timeout)
await new Promise(resolve => eventEmitter.once('consumeDone', ()=>{
console.log("done event");
resolve()
}));
console.log("return");
return result;
// console.log('reading for query finish')
function getMessage(messageCount) {
return msg => {
var content = msg.content.toString();
var secs = content.split('.').length - 1;
result.push(JSON.parse(content));
console.log("deliveryTag:" + msg.fields.deliveryTag)
if (messageCount == deliveryTag) {
console.log(" [x] Done messageCount");
eventEmitter.emit('consumeDone')
channel.cancel(msg.fields.consumerTag)
channel.ack(msg);
channel.close();
channel = null;
}else {
setTimeout(function() {
console.log(" [x] Done");
channel.ack(msg);
}, secs *1000);
}
}
}
}
任何人都遇到这个问题,请帮忙!