从rabbitMQ获取所有消息

时间:2017-02-27 08:32:16

标签: javascript async-await rabbitmq amqp es6-promise

我试图从rabbitMQ队列中获取所有消息。

const messages = await rabbit.getMessages(outputQueue, false);

这是getMessages方法的实现。问题是它只处理3-5条消息并呼叫“解决”问题。一段时间后,它处理休息消息,但“解决”#39;已被调用,无法再次执行。

const amqp = require('amqplib');
.
.
let amqpUrl;
let queueConf;

const init = (connection, queue) => {
  amqpUrl =`amqp://${connection.user}:${connection.password}@${connection.host}:${connectio    n.port}`;
  if (connection.vhost) {
amqpUrl = `amqp://${connection.user}:${connection.password}@${connection.host}:${connection.port}/${connection.vhost}`;
  }
  queueConf = queue;
}

const getChannel = () => new Promise((resolve) => {
  amqp.connect(amqpUrl).then((conn) => {
    conn.createChannel().then((ch) => {
      ch.prefetch(1000).then(() => resolve(ch))
    })
  })
})

module.exports = (connection, queue) => {
  init(connection, queue);
  return {
    getMessages: (queueName, cleanQueue) => new Promise((resolve) => {
      let messages = [];
      let i = 1;
      getChannel().then((ch) => {
        ch.consume(queueName, (msg) => {
          messages.push(msg);
          console.log(msg.content.toString())
        }, { noAck: cleanQueue }).then(() => {
          logger.info(`Retreived ${messages.length} messages from ${queueName}`);
          resolve(messages)
        })
      })
    })
    .
    .
    };
  };

提前致谢!

1 个答案:

答案 0 :(得分:1)

你可以这样做,但它会非常慢,并且如果消息被添加到队列的速度比消耗它们的速度快,则可能永远无法解决。基本上,您一直收到一条消息,直到channel.get()使用false而不是消息对象解析:

getMessages: (queueName, cleanQueue) => {
  let messages = []
  let i = 1
  return getChannel().then(function getMessage (ch) {
    return ch.get(queueName, { noAck: cleanQueue }).then((msg) => {
      if (msg) {
        messages.push(msg)
        return getMessage(ch)
      } else {
        logger.info(`Retrieved ${messages.length} messages from ${queueName}`)
        return messages
      }
    })
  }).catch((err) => {
    err.consumedMessages = messages
    return Promise.reject(err)
  })
}