首页 > 解决方案 > Rabbit MQ amqplib 错误“没有可分配的通道”

问题描述

在 pub sub 模式中工作了一段时间的 rabbit mq workers 之后,我在创建频道时遇到了错误。

Error: No channels left to allocate

标签: node.jsrabbitmq

解决方案


如果您使用https://www.npmjs.com/package/amqplib,您可以使用 Promise 共享频道,同时发布多条消息

message-queue.js

const q = 'tasks';

const open = require('amqplib').connect('amqp://localhost');

const channelPromise = open.then((conn) => conn.createChannel());

// Publisher
function publishMessage(message) {
  channelPromise.then((ch) => ch.assertQueue(q)
    .then((ok) => ch.sendToQueue(q, Buffer.from(message))))
    .catch(console.warn);
}

// Consumer
open.then((conn) => conn.createChannel())
  .then((ch) => ch.assertQueue(q).then((ok) => ch.consume(q, (msg) => {
    if (msg !== null) {
      console.log(msg.content.toString());
      ch.ack(msg);
    }
  }))).catch(console.warn);

module.exports = {
  publishMessage,
};

some-where.js

messageQueue.publishMessage('hello world')

推荐阅读