【问题标题】:Nodejs: Consume rabbitmq messages in topic exchangeNodejs:在主题交换中使用rabbitmq消息
【发布时间】:2019-10-14 06:10:23
【问题描述】:

我正在尝试使用rabbitmq topic exchange。在 rabbitmq 网络管理中,我创建了一个名为 queue1 的队列,其中包含以下详细信息:

创建队列后,我使用默认交换 amq.topic 并使用 anonymous.info 路由键将 queue1 绑定到此交换:

将一些消息推送到此队列1 后:

现在我想使用这些消息,所以我写了这个脚本:

var amqp = require('amqplib/callback_api');
amqp.connect(uri, (error0, connection) => {
    if (error0) {
        throw error0;
    }
    connection.createChannel((error1, channel) => {
        if (error1) {
            throw error1;
        }
        var exchange = 'amq.topic';

        channel.assertExchange(exchange, 'topic', {
            durable: true
        });

        channel.assertQueue('queue1', { exclusive: true, durable: true }, (error2, q) => {
            if (error2) {
                throw error2;
            }
            console.log(' [*] Waiting for logs. To exit press CTRL+C');
            var key = 'anonymous.info';

            channel.bindQueue(q.queue, exchange, key);
            channel.consume(q.queue, function (msg) {
                console.log(" [x] %s:'%s'", msg.fields.routingKey, msg.content.toString());
            }, {
                noAck: true
            });
        });
    });
});

但我收到了这个错误:

Error: Operation failed: QueueDeclare; 405 (RESOURCE-LOCKED) with message "RESOURCE_LOCKED - cannot obtain exclusive access to locked queue 'queue1' in vhost '/'. It could be originally declared on another connection or the exclusive property value does not match that of the original declaration."

所以我将channel.assertQueue() 方法更改为此,意味着我删除了队列名称:

channel.assertQueue('', { exclusive: true, durable: true }, (error2, q) => {
    if (error2) {
        throw error2;
    }

现在我没有收到这些错误,但我没有任何结果。我在 queue1 中有 101 条消息?

channel.assertQueue 回调中q 的结果是:

Object {queue: "amq.gen-Z7PhA8xKdA7v0H_33alxDA", messageCount: 0, consumerCount: 0}

但我没有这个队列名称amq.gen-Z7PhA8xKdA7v0H_33alxDA

它是Temporary queues,但我有一个队列,我想从队列中读取。

【问题讨论】:

  • 我的回答可能有点晚了,但答案是您应该将队列类型从“独占:真”更改为“独占:假”。然后您将能够使用您的消息。问候

标签: node.js rabbitmq


【解决方案1】:

从快照中,您的“queue1”是持久的、非排他性的;并且您的代码尝试使用一个持久、独占的队列

【讨论】:

  • 我将代码更改为channel.assertQueue('', { durable: true }, (error2, q) ,但仍然没有得到任何结果,并且队列名称是别的东西。 @yk42b
  • 我不熟悉 node.js。但是,我认为您可以尝试 channel.assertQueue('queue1', { Durable: true }, (error2, q) @sayreskabir
  • 我有,但我仍然收到Error: Operation failed: QueueDeclare; 405 (RESOURCE-LOCKED) with message "RESOURCE_LOCKED - cannot obtain exclusive access to locked queue 'queue1' in vhost '/'. It could be originally declared on another connection or the exclusive property value does not match that of the original declaration." 错误@yk42b