← Back to the chapter · Previous detail · Next detail →
Technical detail · AMQP Operations: Deployment and Broker Health
Node.js consumer with amqplib
const amqp = require('amqplib');
class AMQPConsumer {
async connect(host, queue, exchange, bindingPatterns, prefetchCount = 10) {
this.connection = await amqp.connect(`amqp://${host}`);
this.channel = await this.connection.createChannel();
this.queue = queue;
// Declare queue with DLX
await this.channel.assertQueue(queue, {
durable: true,
arguments: {
'x-dead-letter-exchange': 'dlx',
'x-dead-letter-routing-key': `${queue}.failed`
}
});
// Bind patterns
for (const pattern of bindingPatterns) {
await this.channel.bindQueue(queue, exchange, pattern);
}
// Set prefetch
await this.channel.prefetch(prefetchCount);
}
async consume(callback) {
console.log(`Consuming from ${this.queue}...`);
this.channel.consume(this.queue, async (msg) => {
if (msg === null) return;
try {
const message = JSON.parse(msg.content.toString());
const success = await callback(message);
if (success) {
this.channel.ack(msg);
} else {
this.channel.nack(msg, false, true); // Requeue
}
} catch (error) {
console.error('Processing error:', error);
this.channel.nack(msg, false, false); // Dead letter
}
}, { noAck: false });
}
}
// Usage
(async () => {
const consumer = new AMQPConsumer();
await consumer.connect(
'localhost',
'analytics',
'sensor-data',
['sensor.#'],
100
);
await consumer.consume((message) => {
console.log('Received:', message);
return true; // Processing successful
});
})();