RabbitMQ - 如何检查队列是否为空? [英] RabbitMQ - How to check if queue is empty?

查看:72
本文介绍了RabbitMQ - 如何检查队列是否为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象 RabbitMQ 服务器的 Web 服务接口(不要问我为什么,我知道这是一个不必要的步骤,但我必须这样做).也就是说,我通过 Web 服务调用从队列中轮询消息,而不是直接通过 amqp.

I have a web service interface that abstracts a RabbitMQ server (don't ask me why, I know it's an unnecessary step, but I have to). That is, I poll messages from the queue through a web service call, not directly over amqp.

Consuming via basic.consumer 阻塞执行线程,直到队列中有消息.这使得 Web 服务不返回.

Consuming via basic.consumer blocks the execution thread till there are messages in the queue. This makes the web service not return.

示例代码:

    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
    $channel = $connection->channel();

    $channel->queue_declare(QUEUE_NAME, false, true, false, false);
    $ret = array('body' => '');

    $callback = function($msg) use ($channel, &$ret) {
        $ret['body'] = $msg->body;
        /*
        Here I would basic.cancel the consumer if there were no messages in the queue
        */
    };

    $channel->basic_consume(QUEUE_NAME, 'tag', false, true, false, false, $callback);

    if (count($channel->callbacks)) {
        $channel->wait(); // blocks here...
    }

    return $ret;

推荐答案

如果想得到队列的大小,可以用php-amqlib调用queue_declare,返回的第二个参数是队列中的消息数.

If you want to get the size of queue, you can call queue_declare with php-amqlib, the second argument of return is the number of messages in the queue.

  list($queue, $messageCount, $consumerCount) = $channel->queue_declare(QUEUE_NAME, true);

在调用 queue_declare() 方法时将 $passive 参数设置为 true 很重要

It is important to give the $passive argument to true when you call the queue_declare() method

这篇关于RabbitMQ - 如何检查队列是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆