How to use the amqplib.connect function in amqplib

To help you get started, we’ve selected a few amqplib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github dial-once / node-bunnymq / src / modules / connection.js View on Github external
getConnection() {
    const url = this._config.host;
    const { hostname } = this._config;
    let connection = this.connections[url];

    // cache handling, if connection already opened, return it
    if (connection && connection.conn) {
      return Promise.resolve(connection.conn);
    }
    // prepare the connection internal object, and reset channel if connection has been closed
    this.connections[url] = {
      conn: null,
      channel: null
    };
    connection = this.connections[url];
    connection.conn = amqp.connect(url, {
      clientProperties: {
        hostname,
        bunnymq: packageVersion,
        startedAt: this.startedAt,
        connectedAt: new Date().toISOString()
      }
    }).then((conn) => {
      // on connection close, delete connection
      conn.on('close', () => {
        delete connection.conn;
      });
      conn.on('error', this._config.transport.error);
      connection.conn = conn;
      return conn;
    }).catch((e) => {
      connection.conn = null;
github danielwii / asuna-node-server / src / modules / providers / mq.provider.ts View on Github external
private async createConnection(): Promise {
    if (MQProvider.enabled) {
      const { url } = MQConfigObject.load();
      logger.log(`connecting to ${url}`);
      const connection = await amqp.connect(url).catch(error => logger.error(`connect to mq error: ${r(error)}`));

      if (connection == null) {
        if (this._retryLimit < 1) {
          process.exit(1);
        }

        setTimeout(
          () =>
            this.createConnection().catch(() => {
              this._retryLimit -= 1;
              logger.error(`reconnect(${10 - this._retryLimit}) to mq error, retry in 10s.`);
            }),
          10000,
        );
        return Promise.reject();
      }
github PacktPublishing / Node.js_Design_Patterns_Second_Edition_Code / ch11 / 08_return_address / amqpRequest.js View on Github external
initialize() {
    return amqp
      .connect('amqp://localhost')
      .then(conn => conn.createChannel())
      .then(channel => {
        this.channel = channel;
        return channel.assertQueue('', {exclusive: true});
      })
      .then(q => {
        this.replyQueue = q.queue;
        return this._listenForResponses();
      })
      .catch(function(err) {
        console.log(err);
      })
    ;
  }
github CharlBest / nean-stack-starter / src / server / broker / broker.ts View on Github external
async init(): Promise {
        try {
            this.connection = await connect(environment.rabbitMQ.amqpUrl);
            this.channel = await this.connection.createChannel();

            for (const queueType in QueueType) {
                if (QueueType.hasOwnProperty(queueType) && queueType) {
                    await this.channel.assertQueue(QueueType[queueType], { durable: true });
                }
            }
        } catch (error) {
            const errorMessage = `Error connecting or creating channels on RabbitMQ`;
            logger.error(errorMessage, [error]);
            throw new Error(error);
        }
    }
github squaremo / amqp.node / examples / tutorials / receive_logs.js View on Github external
#!/usr/bin/env node

var amqp = require('amqplib');

amqp.connect('amqp://localhost').then(function(conn) {
  process.once('SIGINT', function() { conn.close(); });
  return conn.createChannel().then(function(ch) {
    var ok = ch.assertExchange('logs', 'fanout', {durable: false});
    ok = ok.then(function() {
      return ch.assertQueue('', {exclusive: true});
    });
    ok = ok.then(function(qok) {
      return ch.bindQueue(qok.queue, 'logs', '').then(function() {
        return qok.queue;
      });
    });
    ok = ok.then(function(queue) {
      return ch.consume(queue, logMessage, {noAck: true});
    });
    return ok.then(function() {
      console.log(' [*] Waiting for logs. To exit press CTRL+C');
github log4js-node / log4js-node / lib / appenders / rabbitmq.js View on Github external
const con = {
    protocol: 'amqp',
    hostname: host,
    port: port,
    username: username,
    password: password,
    locale: 'en_US',
    frameMax: 0,
    heartbeat: 0,
    vhost: '/',
    routing_key: routingKey,
    exchange: exchange,
    mq_type: type,
    durable: durable,
  };
  const clientconn = amqplib.connect(con);
  clientconn.publish = amqplib.connect(con).publish ? amqplib.connect(con).publish : (client, message) => {
    client.then((conn) => {
      const rn = conn.createChannel().then((ch) => {
        const ok = ch.assertExchange(exchange, type, { durable: durable });
        return ok.then(() => {
          ch.publish(exchange, routingKey, Buffer.from(message));
          return ch.close();
        });
      });
      return rn;
    }).catch(console.error);
  };
  function log(loggingEvent) {
    const message = layout(loggingEvent);
    clientconn.publish(clientconn, message);
  }
github ramesaliyev / mom / services / be-worker / src / lib / rabbitmq.ts View on Github external
constructor({ host, port, user, pass }) {
    this.connection = amqplib.connect({
      protocol: 'amqp',
      hostname: host,
      port: port,
      username: user,
      password: pass,
      heartbeat: 30,
    });
  }
github opencollective / opencollective-api / server / lib / ledger.js View on Github external
export async function postTransactionToLedger(transaction) {
  if (transaction.deletedAt || transaction.type !== 'CREDIT') {
    return Promise.resolve();
  }
  try {
    const ledgerTransaction = await getTransactionWithNestedProperties(transaction);
    if (!process.env.QUEUE_ENABLED) {
      return axios.post(ledger.transactionUrl, ledgerTransaction);
    }
    const conn = await amqp.connect(ledgerQueue.url);
    const channel = await conn.createChannel();
    await channel.assertQueue(ledgerQueue.transactionQueue, { exclusive: false });
    channel.sendToQueue(ledgerQueue.transactionQueue, Buffer.from(JSON.stringify([ledgerTransaction]), 'utf8'));
  } catch (error) {
    debug('postTransactionToLedger error', error);
  }
}
github smooth-code / bundle-analyzer / apps / server / src / services / amqp.js View on Github external
export function connect() {
  if (!amqpConnectionPromise) {
    amqpConnectionPromise = amqp.connect(config.get('amqp.url'))
  }

  return amqpConnectionPromise
}
github ignicaodigitalbr / roger-rabbit / src / modules / connection.js View on Github external
Module.connect = (options) => {
  const { host, context } = options;

  if (channels[host] && channels[host][context]) {
    return new Promise(resolve => resolve(channels[host][context]));
  }

  return amqp.connect(host)
    .then(connection => connection.createConfirmChannel())
    .then((channel) => {
      channels[host] = channel[host] ? channels[host] : {};
      channels[host][context] = channel;

      return channels[host][context];
    })
    .catch((error) => {
      helpers.log('error', error.message, options);

      return error;
    });
};

amqplib

An AMQP 0-9-1 (e.g., RabbitMQ) library and client.

MIT
Latest version published 20 days ago

Package Health Score

91 / 100
Full package analysis