user1187968
user1187968

Reputation: 7986

AMQP (Node.js) for RabbitMQ close connection too early

I have the following code, and it's giving me the following error.

TypeError: Cannot read property 'assertQueue' of undefined
    at /var/www/myapp/dashboard/routes.js:195:39
    at /var/www/myapp/node_modules/amqplib/lib/callback_model.js:46:16
    at /var/www/myapp/node_modules/amqplib/lib/callback_model.js:61:10
    at /var/www/myapp/node_modules/amqplib/lib/callback_model.js:74:5

If I comment out conn.close(), and the code works fine, and I think the code is trying to close the conn too early, before the execution of ch.assertQueue. What is the best way to fix this problem?

amqp.connect('amqp://localhost', function(err, conn) {
  conn.createChannel(function(err, ch) {
    var q = 'blast_queue';
    var msg = blast.id;

    ch.assertQueue(q, {durable: true});
    ch.sendToQueue(q, new Buffer(msg), {persistent: true});
    console.log(" [x] Sent '%s'", msg);
  });
  conn.close();
});

Upvotes: 1

Views: 5400

Answers (2)

This works for me:

From:

amqp.connect('amqp://localhost', function(err, conn) {

To:

amqp.connect({ protocol: 'amqp', hostname: 'localhost', port: 5672, username: 'xxx', password: 'xxx', vhost: '/' }, function(err, conn) {

Upvotes: 0

victorkt
victorkt

Reputation: 14552

This happens because the connection closure happens before the callback function in conn.createChannel is executed. To fix it, move the line where you close the connection inside callback function:

amqp.connect('amqp://localhost', function(err, conn) {
  conn.createChannel(function(err, ch) {
    var q = 'blast_queue';
    var msg = blast.id;

    ch.assertQueue(q, {durable: true});
    ch.sendToQueue(q, new Buffer(msg), {persistent: true});
    console.log(" [x] Sent '%s'", msg);
    conn.close(); // <=== close connection here
  });
});

Upvotes: 2

Related Questions