Search code examples
rabbitmqamqp

How to tell which amqp message was not routed from basic.return response?


I'm using RabbitMQ with node-amqp lib. I'm publishing messages with mandatory flag set, and when there is no route to any queue, RabbitMQ responds with basic.return as in specification.

My problem is that, as far as I can tell, basic.return is asynchronous and does not contain any information about for which message no queue was found. Even when exchange is in confirm mode). How the hell am I supposed to tell which message was returned?


Solution

  • node-amqp emits 'basic-return' event on receiving the basic.return from amqp. Only thing of any use there is routing key. Since all messages with the same routing key are routed the same way. I assumed that once I get a basic.return about a specific routing key, all messages with this routing key can be considered undelivered

    function deliver(routing_key, message, exchange, resolve, reject){
        var failed_delivery = function(ret){
            if(ret.routingKey == routing_key){
                exchange.removeListener('basic-return', failed_delivery);
                reject(new Error('failed to deliver'));
            }
        };
        exchange.on('basic-return', failed_delivery);
        exchange.publish( 
            routing_key,
            message,
            {   deliveryMode: 1, //non-persistent
                mandatory: true
            }, function(error_occurred, error){
                exchange.removeListener('basic-return', failed_delivery);
                if(error_occurred){
                    reject(error);
                } else {
                    resolve();
                }
        });
    }