rabbitmq.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. const Service = require('egg').Service;
  3. class RabbitmqService extends Service {
  4. constructor(ctx) {
  5. super(ctx);
  6. this.exType = 'topic';
  7. this.durable = true;
  8. }
  9. // 发送消息
  10. async sendQueueMsg(ex, routeKey, msg, parm) {
  11. const { mq } = this.ctx;
  12. if (mq) {
  13. await mq.topic(ex, routeKey, msg, parm);
  14. } else {
  15. this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
  16. }
  17. }
  18. // 接收消息
  19. async receiveQueueMsg(ex) {
  20. const self = this;
  21. const { mq } = self.ctx;
  22. if (mq) {
  23. const ch = await mq.conn.createChannel();
  24. try {
  25. await ch.assertExchange(ex, self.exType, { durable: self.durable });
  26. const q = await ch.assertQueue('', { exclusive: true });
  27. // 队列绑定 exchange
  28. await ch.bindQueue(q.queue, ex, '*');
  29. ch.consume(q.queue, msg => {
  30. const result = msg.content.toString();
  31. const headers = msg.properties.headers;
  32. // 插入待办事项到数据库中。
  33. }, { noAck: true });
  34. } catch (e) {
  35. await ch.close();
  36. }
  37. } else {
  38. this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
  39. }
  40. }
  41. }
  42. module.exports = RabbitmqService;