什么是创建Wrapper类以抽象在节点js中使用RabbitMQ的最佳方式或模式

问题描述 投票:0回答:1

所以我正在使用RabbitMQ进行一些项目,我注意到我将使用一些重复的代码,这就是为什么我决定制作一个Wrapper类或接口,它具有一些功能,可以直接使用RabbitMQ而无需一直重复代码。我昨天开始这样做,我已经遇到了一些问题,因为我想使用OOP和Javascript在使用OOP时会很复杂(至少我是这么认为)

我开始用函数init创建一个类IRAbbitMQ来初始化连接并创建一个通道,我知道我不能使用嵌套类,所以我想使用工厂函数,我试图建立连接并通道IRabbitMQ类的一部分属性,但我不知道为什么当我创建它的实例时,这给了我undefined

class IRabbitMQ {

constructor() {

    this.init(rabbitMQServer); // rabbitMQServer for example 'localhost//5672'

}
// establish a Connection to RAbbitMQ Server
async init(host) {

    try {

    let connection = await amqplib.connect(host);

    let channel = await connection.createChannel();

    channel.prefetch(1); 

    console.log(' [x] Awaiting RPC requests');

    this.connection = connection;

    this.channel = channel;

    }

    catch(err) {

        console.error(err);
    }

}

// Close the Connection with RabbitMQ
closeConnection() {

    this.connection.close();
}

log() {
    console.log(this.connection);
}

EventPublisher() {

    function init(IRabbit, publisherName) {

        if(!IRabbit.connection) {

            throw new Error('Create an Instance of IRabbitMQ to establish a Connection');

        }

        let ch = IRabbit.channel;
        console.log(ch);
    }
    return {
        init : init
    }   
    }

   }

   var r = new IRabbitMQ();
   r.log();

当我运行代码输出是未定义的,我不知道为什么因为我初始化init函数中的连接和通道属性,然后在构造函数中调用该函数,以便在我创建Wrapper类的对象时应该初始化。我还想从你那里得到一些建议,使用类是好的还是有更好的方法为RabbitMQ创建一个Wrapper类或接口,以便它易于使用而不必重复代码。

node.js rabbitmq amqp
1个回答
0
投票

不是真正的答案,但我能够使用此示例代码成功记录connection。我修剪了其他代码,只关注记录.log()undefined部分。

代码远非完美,但至少起作用

const amqplib = require('amqplib');

class IRabbitMQ {

    constructor() { }

    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.channel = channel;
        }catch(err) {
            console.error(err);
        }
    }

    log() {
        console.log(this.connection);
    }
}

async function createInstance(){
    const instance = new IRabbitMQ();
    try {
        await instance.init('amqp://localhost');
    }catch (e) {
        throw new Error('OOPS!');
    }
    return instance;
}

async function runLogic() {
    const r = await createInstance();
    r.log();
}

runLogic().catch(console.log);

如果您希望我提供额外的建议/提示,请评论,但这似乎对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.