RabbitMQConnector.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. const amqp = require('amqplib');
  2. const { createLogger } = require('./logger');
  3. const log = createLogger('rabbitmq');
  4. class RabbitMQConnector {
  5. constructor() {
  6. this.connection = null;
  7. this.channel = null;
  8. }
  9. async connect() {
  10. try {
  11. this.connection = await amqp.connect('amqp://username:password@messageBroker');
  12. this.channel = await this.connection.createChannel();
  13. log.info({ action: 'connect', outcome: 'success' });
  14. } catch (error) {
  15. log.error({ action: 'connect', outcome: 'failure', err: error.message });
  16. }
  17. }
  18. async disconnect() {
  19. try {
  20. if (this.channel) {
  21. await this.channel.close();
  22. log.info({ action: 'channel_close', outcome: 'success' });
  23. }
  24. if (this.connection) {
  25. await this.connection.close();
  26. log.info({ action: 'disconnect', outcome: 'success' });
  27. }
  28. } catch (error) {
  29. log.error({ action: 'disconnect', outcome: 'failure', err: error.message });
  30. throw error;
  31. }
  32. }
  33. }
  34. module.exports = RabbitMQConnector;