【问题标题】:How can I build a class to abstract RabbitMQ and amqplib functionality in Node.js如何在 Node.js 中构建一个类来抽象 RabbitMQ 和 amqplib 功能
【发布时间】:2020-04-25 03:27:27
【问题描述】:

我正在尝试构建一个小型库来抽象 amqplib 与 RabbitMQ 通信所需的一些样板。我正在使用 promises api 和 async/await 语法。我正在尝试使用一些方法构建一个类,以与其他几个服务器和客户端一起使用。我在网上搜索过,绝大多数示例都是直接的、小规模的教程。

这是我目前对 messages.js 的了解:

const amqp = require('amqplib');

module.exports = class MQ {
    constructor(user, password, host, port) {
        this.conn;
        this.uri = 'amqp://' + user + ':' + password + '@' + host + ':' + port;
        this.channel;
        this.q = '';
    }
    async setupConnection() {
        this.conn = await amqp.connect(this.uri);
        this.channel = await this.conn.createChannel();

        await this.channel.assertQueue(this.q, { durable: false });
    }   

    send(msg) {
        this.channel.sendToQueue(this.q, Buffer.from(msg));
        console.log(' [x] Sent %s', msg);
    }

    async recv() {
        await this.channel.consume(this.q), (msg) =>{
            const result = msg.content.toString();
            console.log(`Receive ${result}`);
        };
    }
}

这里是 setup.js 的代码:

const MQ = require('./message');

msgq = new MQ('guest', 'guest', 'localhost', '5672')

msgq.setupConnection();

msgq.send('Test this message');

我尝试发送消息时收到的错误是“TypeError:无法读取未定义的属性‘sendToQueue’。”显然通道属性没有被正确初始化。我将 async/await 包含在 try/catch 块中并得到相同的错误。

关于 Node.js 中的类/方法,我有什么遗漏吗?

我认为这与承诺的解决有关。当我将对 sendToQueue() 的调用移至 setupConnection() 方法时,将发送消息。

所以看来我需要找到一种方法让 send 方法等待 setup 方法的解析。

【问题讨论】:

    标签: node.js rabbitmq node-amqplib


    【解决方案1】:

    您没有异步运行代码,因此在建立连接之前调用了 send。在尝试发送之前,您需要链接承诺以确保连接功能已完成。试试这个:

    const MQ = require('./message');
    
    msgq = new MQ('guest', 'guest', 'localhost', '5672')
    
    msgq.setupConnection()
    .then(() => {
        msgq.send('Test this message');
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-08
      • 2018-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      相关资源
      最近更新 更多