← Back to the chapter · Previous detail · Next detail →
Technical detail · AMQP Operations: Deployment and Broker Health
Node.js publisher with amqplib
const amqp = require('amqplib');
class AMQPPublisher {
constructor() {
this.connection = null;
this.channel = null;
}
async connect(host, exchange) {
this.connection = await amqp.connect(`amqp://${host}`);
this.channel = await this.connection.createConfirmChannel();
this.exchange = exchange;
// Declare durable topic exchange
await this.channel.assertExchange(exchange, 'topic', {
durable: true
});
}
async publish(routingKey, message, messageId = null) {
const options = {
persistent: true, // delivery_mode = 2
contentType: 'application/json',
messageId: messageId
};
return new Promise((resolve, reject) => {
this.channel.publish(
this.exchange,
routingKey,
Buffer.from(JSON.stringify(message)),
options,
(err) => {
if (err) reject(err);
else resolve(true);
}
);
});
}
async close() {
await this.channel.close();
await this.connection.close();
}
}
// Usage
(async () => {
const publisher = new AMQPPublisher();
await publisher.connect('localhost', 'sensor-data');
await publisher.publish(
'sensor.temperature.line1.machine3',
{ temp: 75.3, timestamp: Date.now() },
'msg-001'
);
await publisher.close();
})();