UNPKG

doomi-helper

Version:

Doomisoft NodeJs Common Utilities

95 lines (82 loc) 3.34 kB
const path = require('path'); const fs = require('fs'); const _ = require('lodash'); const amqp = require('amqp-connection-manager'); class MessageQueueReceiveHelper { constructor(connectionConfig) { this.consummerQueues = []; if (connectionConfig) { this.connectionConfig = connectionConfig; } else { let config = process.env.CONFIGFILE || 'configuration.json'; let configfile = path.join(process.cwd(), config); // eslint-disable-next-line no-sync if (fs.existsSync(configfile)) { this.config = require(configfile); this.connectionConfig = this.config.messageQueue || {}; } } // Create a connetion manager const { hostname, port, username, password = '', vhost } = this.connectionConfig; this.connection = amqp.connect({ hostname, port, username, password, vhost, }); this.connection.on('connect', function () { console.log('Rabbitmq Receiver Connected!'); }); this.connection.on('disconnect', function (err) { console.log('Rabbitmq Receiver Disconnected.', err.message); }); } /** * 拿到一个队列实例单例 * @returns */ static getSingletonInstance(connectionOption) { if (!MessageQueueReceiveHelper.ProducerInstance) { MessageQueueReceiveHelper.ProducerInstance = new MessageQueueReceiveHelper(connectionOption); } return MessageQueueReceiveHelper.ProducerInstance; } static createInstanceByName(instanceName, connectionOption) { if (!MessageQueueReceiveHelper[instanceName]) { MessageQueueReceiveHelper[instanceName] = new MessageQueueReceiveHelper(connectionOption); } return MessageQueueReceiveHelper[instanceName]; } registerConsummer({ queue, fn: onMessage, fetch = 1 }) { if (MessageQueueReceiveHelper.channels[queue]) { return; } // Set up a channel listening for messages in the queue. MessageQueueReceiveHelper.channels[queue] = this.connection.createChannel({ setup: function (channel) { // `channel` here is a regular amqplib `ConfirmChannel`. return Promise.all([ channel.assertQueue(queue, { durable: true }), channel.prefetch(fetch), channel.consume(queue, async msg => { try { const content = msg.content.toString(); const msgContent = JSON.parse(content); await onMessage(msgContent); } catch (error) { console.log('error:', error); } MessageQueueReceiveHelper.channels[queue].ack(msg); }) ]); } }); MessageQueueReceiveHelper.channels[queue].waitForConnect() .then(function () { console.log(`queue:${queue} Listening for messages`); }); } } MessageQueueReceiveHelper.channels = {}; exports = module.exports = MessageQueueReceiveHelper;