默认情况下,consume()函数会消耗队列中的所有消息,但是我只需要从队列中弹出一条消息,并且下一个consume()调用会弹出队列中的第二条消息,等等。我有这段代码:
rabbit.js (在此文件中我实现了向队列发送和接收):
var amqp = require('amqplib/callback_api');
var ch;
amqp.connect('amqp://localhost', function(err, conn) {
conn.createChannel(function(err, channel) {
ch = channel;
});
});
module.exports.queueSend = function(msg) {
var q = 'hello';
ch.assertQueue(q, {durable: false});
ch.sendToQueue(q, new Buffer(msg));
console.log(" [x] Sent %s", msg);
}
module.exports.queueReceive = function() {
var q = 'hello';
ch.assertQueue(q, {durable: false});
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
ch.consume(q, function(msg) {
console.log(" [x] Received %s", msg.content.toString());
}, {noAck: false});
}
rabbit_test.js (在此文件中我测试了上一代码的功能):
var rabbit = require("./rabbit");
setTimeout(function() {
rabbit.queueSend("01C");
rabbit.queueSend("02C");
rabbit.queueReceive();
}, 2000);
当我调用queueReceive()
函数时,会打印出" 01C"和" 02C"消息,不仅仅是" 01C"。我只需打印" 01C"并在下一个queueReceive()
拨打" 02C"。
P.S。:我在 rabbit.js 中为函数queueReceive()
尝试了此代码:
module.exports.queueReceive = function() {
var q = 'hello';
ch.prefetch(1);
ch.assertQueue(q, {durable: false});
console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);
ch.consume(q, function(msg) {
ch.ack(msg);
console.log(" [x] Received %s", msg.content.toString());
}, {noAck: false});
}
我添加了ch.ack(msg)
和ch.prefetch(1)
部分,但它既不起作用。
我怎样才能使这个工作?谢谢!
答案 0 :(得分:2)
如果您在多个论坛中提问,最好在其中一个论坛中回答您的问题时更新每个论坛。在这种情况下,我在这里回答了你的问题:
https://groups.google.com/d/msg/rabbitmq-users/Py7gx7U0KbI/iWJW7i0WAgAJ