Search code examples
callbackrabbitmqexchange-serverpublishproducer

RabbitMQ Publish to Exchange Confirmation


I would like to return a retrieve a confirmation that the message was successfully published to the exchange before closing the AMQP connection. At the moment, I am using a timeout function to allow for the message to be published before closing the connection. This is not the right way. Can someone please help to retrieve a confirmation so I can close the connection based on a successful publish?

The code I am using is below:

function toExchange(msg)
{
    amqp.connect('amqp://localhost:5672', function(err, conn) //local connection
    {
        conn.createChannel(function(err, ch)
        {
            var exchange = 'MessageExchange';
            ch.assertExchange(exchange, 'fanout', {durable: true});
            ch.publish(exchange, '', new Buffer(msg));
            console.log("Sent to Exchange: %s", msg);
        });
        setTimeout(function() { conn.close(); }, 5000);
    });
}

Solution

  • You can use a RabbitMQ extension called "Publisher confirms". Here is more information: https://www.rabbitmq.com/confirms.html#publisher-confirms.

    You are not notified when the message is published to the exchange, but when it is published and routed to all queues: https://www.rabbitmq.com/confirms.html#when-publishes-are-confirmed

    In your case using amqplib in nodeJS you can use this snippet of code: https://www.squaremobius.net/amqp.node/channel_api.html#confirmchannel

    It uses the callback #waitForConfirms(function(err) {...}) that triggers when all published messages have been confirmed.