doomi-helper
Version:
Doomisoft NodeJs Common Utilities
71 lines (59 loc) • 2.19 kB
JavaScript
const path = require('path');
const fs = require('fs');
const amqp = require('amqp-connection-manager');
class MessageQueueSendHelper {
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 Sender Connected!');
});
this.connection.on('disconnect', function (err) {
console.log('Rabbitmq Sender Disconnected.', err.message);
});
this.init();
}
init() {
// Create a channel wrapper
this.channelWrapper = this.connection.createChannel();
}
/**
* 拿到一个队列实例单例
* @returns
*/
static getSingletonInstance(connectionOption) {
if (!MessageQueueSendHelper.Instance) {
MessageQueueSendHelper.Instance = new MessageQueueSendHelper(connectionOption);
}
return MessageQueueSendHelper.Instance;
}
async sendQueueMessage(queueName, msgParam, durable = true) {
const message = ((typeof msgParam == 'string') ? msgParam : JSON.stringify(msgParam));
try {
await this.channelWrapper.assertQueue(queueName, { durable })
await this.channelWrapper.sendToQueue(queueName, message);
} catch (error) {
console.log('sendQueueMessage error:', error.message);
}
}
}
exports = module.exports = MessageQueueSendHelper;