【问题标题】:Rabbitmq and nodejs delete queue after message has been received收到消息后,Rabbitmq 和 nodejs 删除队列
【发布时间】:2021-12-22 15:33:31
【问题描述】:

我是 rabbitmq 的新手,想弄清楚如何在收到消息后删除队列。任何帮助表示赞赏。这是消费者脚本:

const amqp = require("amqplib");
let result = connect();

async function connect() {

    try {
        const amqpServer = "amqp://localhost"
        const connection = await amqp.connect(amqpServer)
        const channel = await connection.createChannel();
        await channel.assertQueue("jobs");

        channel.consume("jobs", message => {
            const input = JSON.parse(message.content.toString());
            console.log(`Recieved job with input ${input}`);
        })
        console.log("Waiting for messages...");
    } catch (ex) {
        console.error(ex)
    }
}

【问题讨论】:

  • 您是要从队列中删除消息还是删除队列?
  • 收到消息后尝试删除队列
  • 在下面查看我的答案。

标签: node.js rabbitmq


【解决方案1】:

根据assertQueue queue docs,您可以在创建时传递一个autoDelete选项,在消费者数量下降到0后将其清理。

const amqp = require("amqplib");
let result = connect();

async function connect() {

    try {
        const amqpServer = "amqp://localhost"
        const connection = await amqp.connect(amqpServer)
        const channel = await connection.createChannel();
        await channel.assertQueue("jobs", {autoDelete: true});

        channel.consume("jobs", message => {
            const input = JSON.parse(message.content.toString());
            console.log(`Recieved job with input ${input}`);
        })
        console.log("Waiting for messages...");
    } catch (ex) {
        console.error(ex)
    }
}

然后您可以在频道上调用cancel 以停止消费消息。

channel.cancel("jobs");

最后,您可以使用deleteQueue 强制删除队列,但如果在回调中执行此操作可能会产生一些奇怪的副作用。

【讨论】: