admin管理员组文章数量:1416651
I'm working with RabbitMQ in a Node.js application and have created a class that manages the connection and channel. The class exports the channel
, and it works fine the first time I use it. However, when I try to reuse the same channel
in another function, I get the following error:
Error while starting the worker ReferenceError: rabbitMqInstance is not defined
at dbWorker (file:///D:/Projects/Practice_2/Notification-system/src/worker/db.worker.js:4:21)
at file:///D:/Projects/Practice_2/Notification-system/src/worker/db.worker.js:25:1
at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
at async ModuleLoader.import (node:internal/modules/esm/loader:473:24)
at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)
RabbitMq Connection
class RabbitMq {
constructor() {
this.connection;
this.channel;
}
async connect() {
try {
this.connection = await amqp.connect(process.env.RABBITMQ_URL);
this.channel = await this.connection.createChannel();
console.log("connected to rabbitMQ successfully");
} catch (error) {
console.log("something went wrong while connection to rabbitMq", error);
process.exit(1);
}
}
getChannel() {
if (!this.channel) {
throw new Error("RabbitMq is not connected");
}
return this.channel;
}
}
export const rabbitMqInstance = new RabbitMq();
Worker
const channel = rabbitMqInstance.getChannel();
channel.assertQueue("db-queue");
channel.consume("db-queue", (msg) => {
console.log(msg.content.toString());
});
channel.ack(msg);
// const connection = await amqp.connect(process.env.RABBITMQ_URL);
// const channel = await connection.createChannel();
channel.assertQueue("db-queue", { durable: true });
channel.consume("db-queue", (msg) => {
console.log(msg.content.toString());
channel.ack(msg);
});
- I want to create a single connection and reuse the same RabbitMQ channel across my application.
- The
channel
should remain available for multiple function calls instead of becomingundefined
.
本文标签: nodejsExported Channel Becomes Undefined on Second UseStack Overflow
版权声明:本文标题:node.js - Exported Channel Becomes Undefined on Second Use - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745255691a2650086.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论