2

How can I send an array of messages using RabbitMQ? I do not want to send every message separately.

For example:

ch.publish(ex, '', new Buffer('hello world'));

How could I use something like:

ch.publish(ex, '', new Buffer([msg1, msg2, msg3...]));

Thank you!

sdexp
  • 756
  • 4
  • 18
  • 36
user2573863
  • 643
  • 1
  • 9
  • 18

3 Answers3

2

You can pass JSON through like so:

var json = JSON.stringify(arr);
ch.publish(ex, '', new Buffer(json));

Then the consumer would parse the JSON.

Edward
  • 2,291
  • 2
  • 19
  • 33
1

How could I send array of messages using RabbitMQ? I do not want to send every message separately.

You can't. Each message must be sent individually.

If you tried to do what you want, you would end up with a single "message" that contained all of the individual messages you wanted to send.

If you want to make an API that looks like you can do this, just create a function that takes an array of messages, loops through them and sends them one at a time.

(nodejs / amqplib)

function publishAll(ex, ...messages){
  return messages.map((msg) => {
    ch.publish(ex, '', msg);
  });
}

var pub = publishAll("my.exchange", [msg1, msg2, msg3]);
pub.then(() => {
  // run code after they are all published
});
Derick Bailey
  • 72,004
  • 22
  • 206
  • 219
0

I addition to what @derick-bailey said, if you need more than one variable to be sent in each message you could always make a string with the variables comma separated. Or, if you'll use commas in the text you can find some other symbol that will work.

sdexp
  • 756
  • 4
  • 18
  • 36