0

I'm writing a simple server app using nodejs and i want to use rabbitmq as a message broker with other services. My problem is that i don't understand how can i reuse the channel object created asynchronously inside other files?

RabbitMQ has the following samle:

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(err, conn) {
  conn.createChannel(function(err, ch) {
    var q = 'hello';
    var msg = 'Hello World!';

    ch.assertQueue(q, {durable: false});
    ch.sendToQueue(q, new Buffer(msg));
    console.log(" [x] Sent %s", msg);
  });
  setTimeout(function() { conn.close(); process.exit(0) }, 500);
});

I want to achieve something like that:

var channel = require('channelcreation');
// some express.js router logic
router.get('path', function(req, res) {
    . . .
    channel.send(...);
    . . .
})
Nikita Ryanov
  • 1,520
  • 3
  • 17
  • 34
  • 1
    I think what you'll want to do is export a Promise or async `connect()` function that your other code can await when the app starts up. You'll almost certainly need to abstract your `channel.send()` out of your express router and into a layer that can gracefully throw an error to the route if the AMQP connection failed or isn't ready yet. – Josh Apr 08 '18 at 20:22
  • At this moment, i think that it is the only option – Nikita Ryanov Apr 08 '18 at 20:33
  • What do you mean by "reuse the channel object?" – theMayer Apr 09 '18 at 17:06
  • @theMayer, i mean that i want to send\publish messages dynamically from anywhere of my project, not only inside callback function which i can't call on demand – Nikita Ryanov Apr 09 '18 at 20:10
  • 1
    You should create a new channel object for that. See a longer explain in my answer at the bottom of this https://stackoverflow.com/questions/18418936/rabbitmq-and-relationship-between-channel-and-connection – theMayer Apr 09 '18 at 20:11
  • But in this case i have to get connection object, which, again, is created async. The main problem for me is that i don't understand how to get is in sync mode. – Nikita Ryanov Apr 09 '18 at 20:14

0 Answers0