如何将RabbitMQ连接分配给类的属性以在另一个函数中使用它?

时间:2019-04-10 08:03:35

标签: javascript node.js rabbitmq amqp

因此,主要思想是创建一个Wrapper类,该类包含一些函数,以使其更易于使用Rabbitmq的发布,订阅和RPC功能。例如,目标是,如果我要发布某些内容,则可以轻松使用Rabbit Wrapper类中的发布功能,例如,它看起来像这样:var rabbit = new IRabbitMQ();,然后使用发布者进行发布函数rabbit.publisher(exchangeName, queueName, etc..),如果我有兴趣接收,那么我会很容易地致电rabbit.subscriber(exchangeName, queueName, etc..)

我尝试了所有想法,但不适用于嵌套类,因为在js中,我找不到方便的方法,还尝试了工厂函数或简单对象,避免使用类,但是没有工作。问题始终是,当我建立连接并在我和RabbitMQ之间创建通道时,如果我想

,则无法将该连接和通道存储在Wrapper类的Property中以在其他函数中使用它
 class IRabbitMQ {

constructor() {
   this.init(rabbitMQServer); // this should initialize my this.connection and this.channel property to the connection and channel object but instead receive an error because there are undefined
 }

async init(host) {
    try {
        const connection = await amqplib.connect(host);
        const channel = await connection.createChannel();
        channel.prefetch(1);
        console.log(' [x] Awaiting RPC requests');
        this.connection = connection; // this should make a property connection with the connection object, when i console.log here it shows me the connection object but if i want to use this in another function it gaves me undefined value!
        this.channel = channel;
    }catch(err) {
        console.error(err);
    }
}

async publisher(queue, body) {

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

    this.channel.sendToQueue(q, Buffer.from(JSON.stringify(body)));

    console.log("msg sent ", body);
}

async subsriber(queue) {

    let q = await this.channel.assertQueue(queue, {durable: false});
    console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);

    await  this.channel.consume(q, function(msg) {
        console.log(" [x] Received %s", msg.content.toString());
      }, {noAck: true});
}


}

   // another example using a simple object instead of a class
      /* var IRabbitMQ = {

channel : undefined, 

init : async (host) => {

    try {
        const connection = await amqplib.connect(host);
        const channel = await connection.createChannel();
        channel.prefetch(1);
        console.log(' [x] Awaiting RPC requests');
        this.channel = channel;

    }catch(err) {
        console.error(err);
    }
},

publisher : async (queue, body) =>{
    this.init(rabbitMQServer);
    let q = await this.channel.assertQueue(queue, {durable: false});

    this.channel.sendToQueue(q, Buffer.from(JSON.stringify(body)));

    console.log("msg sent ", body);
},

subscriber : async(queue) => {
    this.init(rabbitMQServer);
    let q = await this.channel.assertQueue(queue, {durable: false});
    console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", q);

    await  this.channel.consume(q, function(msg) {
        console.log(" [x] Received %s", msg.content.toString());
      }, {noAck: true});
}

   } */

预期的输出是,我可以访问connection和channel的值,以便稍后在其他函数中使用它,因为如果不这样做,则创建Wrapper类将没有意义。如果你们也从自己的经验中得到了更好的想法,这将有助于倾听。

0 个答案:

没有答案