项目作者: alexvanzyl

项目描述 :
Fastify RabbitMQ connection plugin, this is a convenience wrapper around amqplib library.
高级语言: JavaScript
项目地址: git://github.com/alexvanzyl/fastify-rabbit.git
创建时间: 2019-06-26T09:03:47Z
项目社区:https://github.com/alexvanzyl/fastify-rabbit

开源协议:MIT License

下载


fastify-rabbit

js-standard-style
Build Status

Fastify RabbitMQ connection plugin, this is a convenience wrapper around amqplib library.

Install

  1. npm i fastify-rabbit --save

Usage

  1. const fastify = require('fastify')()
  2. // Register plugin
  3. fastify.register(require('fastify-rabbit'), {
  4. url: 'amqp://localhost'
  5. })
  6. // Publish message to queue
  7. fastify.get('/', async function (req, reply) {
  8. const channel = this.rabbit.channel
  9. // Create queue if it does not exist
  10. const ok = await channel.assertQueue('hello')
  11. if (!ok) {
  12. // handle failed to assert queue
  13. }
  14. // Push message to queue
  15. try {
  16. await channel.sendToQueue('hello', Buffer.from('The is my message to you...'))
  17. reply.send('Message sent!')
  18. } catch (err) {
  19. reply.log.error(err)
  20. }
  21. })
  22. // Consume messages from queue
  23. fastify.register(async function(fastify, opts) {
  24. const channel = fastify.rabbit.channel
  25. // Create queue if it does not exist
  26. const ok = await channel.assertQueue('hello')
  27. if (ok) {
  28. // start consuming queue
  29. channel.consume('hello', msg => {
  30. fastify.log.info(msg.content.toString())
  31. channel.ack(msg)
  32. })
  33. }
  34. })

Using connection object

You can also connect using an object instead of an url, like so:

  1. fastify.register(require('fastify-rabbit'), {
  2. protocol: 'amqp',
  3. hostname: 'localhost',
  4. port: 5672,
  5. username: 'guest',
  6. password: 'guest',
  7. locale: 'en_US',
  8. frameMax: 0,
  9. heartbeat: 0,
  10. vhost: '/'
  11. })

Reference

This plugin decorates the fastify instance with a rabbit object. That object has the
following properties:

Running tests

To run tests RabbitMQ is required. You can either install it via a package manager or if you have docker installed you can spin up a RabbitMQ container with:

  1. npm run rabbit

Under the hood this runs docker run -p 5672:5672 -p 15672:15672 rabbitmq:management.

You can now run the tests with:

  1. npm test

License

Licensed under MIT.