首页 > 解决方案 > RabbitMQ auto_delete 选项不起作用

问题描述

我正在关注 RabbitMQ 上的教程 #2 ( https://www.rabbitmq.com/tutorials/tutorial-two-python.html ),但我想稍微改变一下。

我希望我的队列 auto_delete 一旦 100% 被消耗,但事实并非如此。我哪里错了?

我的生产者代码:

var amqp = require('amqplib/callback_api');


const RABBIT_MQ_HOST = 'amqp://localhost'

amqp.connect(RABBIT_MQ_HOST, function(error0, connection){
    if(error0){
        throw error0;
    }
    connection.createChannel(function(error1, channel){
        if(error1){
            throw error1;
        }

        const queue = 'task_queue';
        const msg = process.argv.slice(2).join(' ') || "Hello World!";

        channel.assertQueue(queue, {
            durable: true,
            auto_delete: true,
        });

        channel.sendToQueue(queue, Buffer.from(msg), {
            persistent: true,
        });
        console.log('[x] Sent %s', msg);
    });
    setTimeout(function() {
        connection.close();
        process.exit(0)
        }, 500);
});

我的消费者代码:

var amqp = require('amqplib/callback_api');

const RABBIT_MQ_HOST = 'amqp://localhost'

amqp.connect(RABBIT_MQ_HOST, function(error, connection) {
    connection.createChannel(function(error, channel) {
        var queue = 'task_queue';

        channel.assertQueue(queue, {
            durable: true,
            auto_delete: true,
        });
        channel.prefetch(1);
        console.log(" [*] Waiting for messages in %s. To exit press CTRL+C", queue);
        channel.consume(queue, function(msg) {
            var secs = msg.content.toString().split('.').length - 1;

            console.log(" [x] Received %s", msg.content.toString());
            setTimeout(function() {
                console.log(" [x] Done");
                channel.ack(msg);
            }, secs * 1000);
        }, {
            noAck: false
        });
    });
});

在启动生产者代码,然后是消费者代码后,最后我的队列是空的,但没有被删除。

我究竟做错了什么 ?

谢谢

标签: node.jsrabbitmq

解决方案


自动删除队列在其最后一个消费者被取消时被删除,而不是在队列为空时被删除。

请参阅文档

当最后一个消费者被取消(例如使用 AMQP 0-9-1 中的 basic.cancel)或消失(关闭通道或连接,或与服务器的 TCP 连接丢失)时,自动删除队列将被删除。


推荐阅读