I'm using a RabbitMQ queue to publish and receive messages between consumers, the main issue is that I want to receive a single message then exit. From other answers on this site I've seen that channel.get
seems to be the best way to do this. However, I can't get it to work. This is the answer I've been using.
My current code:
var amqpChannel = null;
var queue = "test";
amqp.connect(cluster, (error0, connection) => {
if (error0) throw error0;
connection.createChannel((error1, channel) => {
if (error1) throw error1;
amqpChannel = channel;
});
});
var readMessage = function() {
if (amqpChannel)
{
amqpChannel.get(queue, (err, msg) => {
if (err) console.log(err);
if (msg)
{
console.log("Message received: " + msg.content.toString());
amqpChannel.ack(msg);
}
});
}
}
setTimeout(readMessage, 1000);
As far as I can see, it is identical to the code in the accepted answer above, however I can't seem to get it to work. What am I missing?
Edit: Extra info
Using channel.consume
works for me, it gets whatever messages are in the queue. However using the channel.get
method results in nothing. I have used console.log
lines to ensure the channel is being created properly, but for some reason the channel.get
callback is never being triggered. I know that all the connection and queue creation is all working, I just can't seem to get the channel.get
method to trigger at all.
Edit 2: I found the issue
My callback function wasn't correct. Looking at the documentation here, channel.get
requires an options
parameter before the callback, adding that in fixed my issue. My working code is now:
var amqpChannel = null;
var queue = "test";
amqp.connect(cluster, (error0, connection) => {
if (error0) throw error0;
connection.createChannel((error1, channel) => {
if (error1) throw error1;
amqpChannel = channel;
});
});
var readMessage = function() {
if (amqpChannel)
{
amqpChannel.get(queue, {noAck: true}, (err, msg) => {
if (err) console.log(err);
if (msg)
{
console.log("Message received: " + msg.content.toString());
amqpChannel.ack(msg);
}
});
}
}
setTimeout(readMessage, 1000);