egg-amqplib-plugin
TypeScript icon, indicating that this package has built-in type declarations

1.0.5 • Public • Published

egg-amqplib-plugin

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Install

$ npm i egg-amqplib-plugin --save

Usage

// {app_root}/config/plugin.js
exports.amqplib = {
  enable: true,
  package: 'egg-amqplib-plugin',
};

Configuration

// {app_root}/config/config.default.js
'use strict';

/**
 * egg-amqplib-plugin default config
 * @member Config#amqplib
 * @property {String} SOME_KEY - some description
 */
exports.amqplib = {
  app: true,
  agent: false,
  // url: 'amqp:localhost'
  options: {
    protocol: 'amqp',
    hostname: 'localhost',
    port: 5672,
    username: 'guest',
    password: 'guest',
    locale: 'en_US',
    frameMax: 0,
    heartbeat: 0,
    vhost: '/',
  },
  // socketOptions: {
  //   cert: certificateAsBuffer, // client cert
  //   key: privateKeyAsBuffer, // client key
  //   passphrase: 'MySecretPassword', // passphrase for key
  //   ca: [caCertAsBuffer], // array of trusted CA certs
  // },
};

see config/config.default.js for more detail.

Example

const Service = require('egg').Service;

class AmqpService extends Service {
  /**
   * send message to rabbitMq
   * @param {{ [key: string]: any; }} msg msg
   * @param {'mining' | 'crowdfund'} type mining or crowdfund
   * @return {Promise<boolean>} res
   */
  async send(msg, type) {
    const { ctx, app, config } = this;
    try {
      msg = JSON.stringify(msg);

      const {
        source,
        client: {
          exchange: { name },
        },
      } = config.amqplib;
      const routingKey = source[type];

      if (!routingKey) {
        ctx.logger.warn('unknown rabbitMq source type.');
        return;
      }
      // 向交换机指定路由发送信息
      app.amqplib.publish(name, routingKey, Buffer.from(msg));
      ctx.logger.info(" [x] Sent %s:'%s' ", routingKey, msg);
      return true;
    } catch (err) {
      ctx.logger.error('send rabbitMQ error:', err);
      throw err;
    }
  }
}

module.exports = AmqpService;

Questions & Suggestions

Please open an issue here.

License

MIT

Package Sidebar

Install

npm i egg-amqplib-plugin

Weekly Downloads

0

Version

1.0.5

License

MIT

Unpacked Size

12.7 kB

Total Files

8

Last publish

Collaborators

  • daipengfei