user2573863
user2573863

Reputation: 683

Send array via RabbitMQ

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!

Upvotes: 2

Views: 5849

Answers (3)

Edward
Edward

Reputation: 2359

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.

Upvotes: 2

sdexp
sdexp

Reputation: 776

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.

Upvotes: 0

Derick Bailey
Derick Bailey

Reputation: 72868

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
});

Upvotes: 1

Related Questions