首页 > 解决方案 > 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 。

标签: node.jsrabbitmqamqpnode-amqplib

解决方案


推荐阅读