Here is the producer code:
import * as amqp from "amqplib";
export default class Producer {
channel;
async createChannel() {
const connection = await amqp.connect("amqp://localhost");
this.channel = await connection.createChannel();
}
async publishMessage(routingKey, message) {
if (!this.channel) {
console.log("called");
await this.createChannel();
}
const exchangeName = "loggerEx";
await this.channel.assertExchange(exchangeName, "direct");
const logDetails = {
logType: routingKey,
message: message,
dateTime: new Date(),
};
await this.channel.publish(
exchangeName,
routingKey,
Buffer.from(JSON.stringify(logDetails))
);
console.log(`The new ${routingKey} log is sent to exchange ${exchangeName}`);
}
}
Here is how I am using Producer class:
server.js
import Producer from "./producer.js";
const producer = new Producer();
producer.publishMessage("info", "somemessage");
producer.publishMessage("info", "somemessage");
In RabbitMQ management UI, I see two connections:
In Producer class I am checking for the existence of the channel.
if (!this.channel) {
console.log("called");
await this.createChannel();
}
then why connection is being created multiple times.
Here is the output when I run the file:
$ node server.js
called
called
The new info log is sent to exchange loggerEx
The new info log is sent to exchange loggerEx

Okay, it was due to the missing
awaitkeyword: