RabbitMQ Consumer Code Examples
Here you can find consumers examples using different programming languages.
The official RabbitMQ site contains a very useful tutorial with code examples. But if you want to run your consuming application right now, you can use examples on this page
Connection parameters
All of these examples use the following connection parameters:
Protocol:
AMQP - if you don’t use SSL connection
AMQPS - if you use SSL connection. This protocol is used by default on AWS managed RabbitMQ.
Hostname
Username
Password
Port (usually it is 5671 or 5672)
Virtual hostname (vHost)
Exchange name
Queue name
All our examples use exchange type “direct” and “durable” exchanges and queues.
Examples
JavaScript
Java script example code uses package amqplib
. Please, install the package before proceeding with an example:
npm install amqplib
Now you are able to fill in your connection parameters into the script and start consuming:
#!/usr/bin/env node
var amqp = require('amqplib/callback_api');
var broker_url = 'amqps://<username>:<password>@<host>:<port>/<vhost>'
var exchange = '<exchange_name>'
var queue = '<queue_name>'
amqp.connect(broker_url, function(error0, connection) {
if (error0) {
throw error0;
}
connection.createChannel(function(error1, channel) {
if (error1) {
throw error1;
}
channel.assertExchange(exchange, 'direct', {
durable: true
});
channel.assertQueue(queue, {
durable: true
}, function(error2, q) {
if (error2) {
throw error2;
}
channel.bindQueue(q.queue, exchange, queue);
console.log(' [*] Waiting for data. To exit press CTRL+C');
channel.consume(q.queue, function(msg) {
console.log(" [x] %s: '%s'", msg.fields.routingKey, msg.content.toString());
}, {
noAck: true
});
});
});
});
Python
Python example uses package pika
:
pip install pika
This example code is able to run with using Python 3.6 or higher. You can remove f-string using and run the code on earlier Python3 version.