AMQPConnector.ts 980 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
import { Channel, connect, Connection } from 'amqplib';
import { settings } from '../statistics';

class AMQPConnector {
  private static _instance: AMQPConnector;

  private _channel: Channel;

  get channel(): Channel {
    return this._channel;
  }

  private _connection: Connection;

  constructor() {
  }

  public static getInstance(): AMQPConnector {
    if (!this._instance) {
      this._instance = new AMQPConnector();
    }

    return this._instance;
  }

  public async initConnection(): Promise<void> {
    this._connection = await connect({
      protocol: settings.amqp.protocol,
      hostname: settings.amqp.hostname,
      username: settings.amqp.user,
      password: settings.amqp.password,
32
      vhost: settings.amqp.vhost,
33 34
    });
    this._channel = await this._connection.createChannel();
35 36 37
    this._channel.on('error', error => {
      console.error('Exception in amqp channel occured', error);
    });
38 39 40 41
  }
}

export default AMQPConnector.getInstance();