rabbitmq.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. console.log(ex);
  21. const self = this;
  22. const { mq } = self.ctx;
  23. if (mq) {
  24. const ch = await mq.conn.createChannel();
  25. try {
  26. await ch.assertExchange(ex, self.exType, { durable: self.durable });
  27. const q = await ch.assertQueue('', { exclusive: true });
  28. console.log('==q=', q);
  29. // 队列绑定 exchange
  30. await ch.bindQueue(q.queue, ex, '*');
  31. const getResult = async () => {
  32. return new Promise(resolve => {
  33. ch.consume(q.queue, msg => {
  34. ch.close();
  35. resolve(msg);
  36. }, { noAck: true });
  37. });
  38. };
  39. const resultMq = await getResult();
  40. if (resultMq != null) {
  41. const headers = resultMq.properties.headers;
  42. const data = { userid: headers.userid, type: '0', status: '0' };
  43. const dataimpResult = await this.ctx.service.dataimp.query(data);
  44. await this.ctx.service.excelimport.getImportXLSXData(dataimpResult);
  45. }
  46. } catch (e) {
  47. console.log('==e==', e);
  48. await ch.close();
  49. }
  50. } else {
  51. this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
  52. }
  53. }
  54. }
  55. module.exports = RabbitmqService;