node.js - rabbitMQ 重启后使用 amqplib 重新连接 RabbitMQ
问题描述
我有这个 rabbitmq 连接代码,我使用它连接到队列并使用它。
const amqp = require('amqplib');
class RabbitMq {
constructor(connStr) {
this.connStr = connStr;
this.conn = null;
this.channel = null;
this.queues = {};
this.isConnecting = false;
}
async connect() {
if (this.conn) return;
this.conn = await amqp.connect(this.connStr);
}
async getChannel() {
if (this.channel) return this.channel;
if (!this.conn) await this.connect();
this.channel = await this.conn.createChannel();
return this.channel;
}
async sendToQueue(queue, message) {
if (!this.channel) await this.getChannel();
return this.channel.sendToQueue(
queue,
Buffer.from(JSON.stringify(message))
);
}
async consume(queue, handler) {
if (!this.conn) await this.connect();
if (!this.channel) await this.getChannel();
await this.channel.assertQueue(queue);
this.channel.prefetch(1);
this.channel.consume(queue, handler);
}
async assertQueue(queue) {
if (!this.channel) await this.getChannel();
await this.channel.assertQueue(queue);
}
async ack(message) {
if (!this.channel) await this.getChannel();
this.channel.ack(message);
}
}
// handle SIGTERM, SIGINT
module.exports = new RabbitMq(process.env.CLOUDAMQP_URL);
现在这工作正常,但只要我在终端上运行这个命令,
brew services restart rabbitmq
这基本上是重新启动rabbitMQ,我收到这个心跳错误,然后我无法再次连接到rabbitMQ。这种情况不断发生。我还尝试将 try catch 放入connect()
函数中,但它没有被捕获。我得到的错误是:
Error: Heartbeat timeout
at Heart.<anonymous> (/Users/..../node_modules/amqplib/lib/connection.js:427:19)
at Heart.emit (events.js:315:20)
at Heart.runHeartbeat (/Users/..../node_modules/amqplib/lib/heartbeat.js:88:17)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
有什么想法吗?如果有办法可以捕获此异常,那么我可以从那里再次调用 connect 。
解决方案
推荐阅读
- arrays - 如何附加引号使其成为字符串数组?
- postgresql - 如何通过命令提示符备份或导出 Postgres 数据库
- mysql - 字符串操作 W3Resources
- html - 图像悬停样式无法实现
- javascript - 使用 Javascript 和单选按钮显示文本文件
- javascript - 在段落标记内插入选定文本的 HTML 标记
- ruby-on-rails - 共享点提供商在 Visual Studio 2017 中托管应用程序以在组织级别发布
- java - Spring RequestMapping 不会在 .jsp 请求上触发
- ios - 在使用 swift 的 iOS 中,如何创建一个始终位于整个应用程序顶部的可拖动和浮动 UIView
- python - Jupyter notebook 多窗口输出