RabbitMQ 创建多个连接

问题描述 投票:0回答:1

这是生产者代码:

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
node.js rabbitmq amqp node-amqplib
1个回答
0
投票

好的,这是因为缺少

await
关键字:

await producer.publishMessage("info", "somemessage");
await producer.publishMessage("info", "somemessage");
© www.soinside.com 2019 - 2024. All rights reserved.