Rabbitmq Node.js关闭连接

问题描述

我对Rabbitmq有疑问。

我想知道是否在发送“发布”消息时需要关闭与消费者的通道连接和amqpblib连接?还是正确的方法是保持连接打开?

我有这个要发布和订阅

public produce = async <T>(queue: string,message: T): Promise<boolean> => {
    try {
      if (!this.connection) await this.start();
      await this.initChannel(queue);
      const sendResult = this.channel.sendToQueue(queue,Buffer.from(message),{
        persistent: true,});
      if (!sendResult) {
        await new Promise(resolve => this.channel.once('drain',() => resolve));
      }
      return sendResult;
    } catch (error) {
      Logger.info(error.message);
      return false;
    } finally {
      this.close();
    }
  };

订阅

public subscribe = async (
    queue: string,onMessage: (msg: IMessage) => boolean,): Promise<void> => {
    if (!this.connection) await this.start();
    const channel = await this.initChannel(queue);
    channel.consume(queue,message => {
      if (!message) return false;
      const body = <IMessage>JSON.parse(message.content.toString());
      if (body && onMessage(body)) onMessage(body);
      channel.ack(message);
    });
  };

这是初始化连接和侦听器事件:

private start = async () => {
    try {
      this.connection = await connect(this.rabbitUrl);
      Logger.info('connect to RabbitMQ success');
      await this.listeners();
    } catch (err) {
      Logger.info(err.message);
      sleep(this.start,10000);
    }
  };

private listeners = async (): Promise<Connection> => {
    return (
      this.connection.on('error',(err: Error) => {
        Logger.info(err.message);
        sleep(this.start,10000);
      }) &&
      this.connection.on('close',() => {
        Logger.info('connection to RabbitQM closed!');
        sleep(this.start,10000);
      })
    );
  };

解决方法

创建连接很昂贵,通道很轻巧,但在大多数客户端中都是线程不安全的。

对于Node.js应用程序(单线程模型),理想情况下,publishsubscribe只有两个连接,每个连接一个通道。

所以请保持连接和通道打开。