var Connection = require('./Connection');
var Channel = require('./Channel');
var Exchange = require('./Exchange');
var Queue = require('./Queue');
var Consume = require('./Consume');
var ExchangeTypes = require('../constant').ExchangeTypes;
var RouteKey = require('../constant').RouteKey;
var config = require('../../config');
var log = require('../../common/logger').getLogger('Core:mq:index');
var ROUTE_KEY = RouteKey.RECEIVE_PA;
var QUEUE_NAME = RouteKey.RECEIVE_PA;
function MQ() {
this.connection = null;
this.init();
}
MQ.prototype.init = function init() {
var self = this;
Connection
.createConnection(config.rabbitMQ_url)
.then(function (conn) {
self.connection = conn;
conn.on('error', function(err) {
log.error('[mq] connection error ', err);
self.reconnect();
});
log.info('[mq] create connection success');
return Channel
.createChannel(conn);
})
.then(function (ch) {
process.once('SIGINT', function() {
log.info('kill by signal SIGINT');
ch.close();
self.connection.close();
self.connection = null;
process.exit(0);
});
ch.on('error', function(error) {
log.error('[mq] channel error: ', error);
});
log.info('[mq] create channel success');
return Exchange
.assertExchange(ch, config.exchange_name, ExchangeTypes.DIRECT, {durable: false})
.then(function () {
log.info('[mq] assert exchange [%s] [%s]', config.exchange_name, ExchangeTypes.DIRECT);
return Queue
.assertQueue(ch, QUEUE_NAME, {exclusive: false, durable: false});
})
.then(function (queue) {
log.info('[mq] assert queue [%s] success', QUEUE_NAME);
log.debug(queue);
return Queue.
bindQueue(ch, QUEUE_NAME, config.exchange_name, ROUTE_KEY);
})
.then(function() {
log.info('[mq] bind queue [%s] to exchange [%s]', QUEUE_NAME, config.exchange_name);
return Consume
.consume(self.connection, ch, QUEUE_NAME);
})
})
.catch(function (err) {
log.error('[mq] Init failed , error: ', err);
self.reconnect();
});
};
MQ.prototype.reconnect = function() {
var self = this;
log.info('[mq] try reconnect 3 seconds later');
setTimeout(function () {
self.init();
self.reconnectCount++;
}, 3000);
}
MQ.prototype.getConnection = function getConnection() {
var self = this;
if (this.connection) {
return Promise.resolve(self.connection);
} else {
return Connection
.createConnection(config.rabbitMQ_url)
.then(function (conn) {
self.connection = conn;
process.once('SIGINT', function() {
log.info('kill by signal SIGINT');
conn.close();
self.connection = null;
process.exit(0);
});
log.info('[mq] create connection success');
return Promise.resolve(conn);
});
}
}
module.exports = MQ;