这是生产者代码:
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}`);
}
}
这是我如何使用
Producer
类:
服务器.js
import Producer from "./producer.js";
const producer = new Producer();
producer.publishMessage("info", "somemessage");
producer.publishMessage("info", "somemessage");
在 RabbitMQ 管理 UI 中,我看到两个连接:
在
Producer
课程中,我正在检查通道是否存在。
if (!this.channel) {
console.log("called");
await this.createChannel();
}
那么为什么会多次创建连接。
这是我运行文件时的输出:
$ node server.js
called
called
The new info log is sent to exchange loggerEx
The new info log is sent to exchange loggerEx
好的,这是因为缺少
await
关键字:
await producer.publishMessage("info", "somemessage");
await producer.publishMessage("info", "somemessage");