php - 使用 PhpAmqpLib 从 rabbitmq 消费者的回调中获取队列大小

标签 php rabbitmq queue php-amqplib

我想从 worker 的回调中记录工作状态,并在左边的队列中包含一些消息。

到目前为止我找到的唯一解决方案是获取 queue_declare 的第二个成员结果数组,但是每次工作启动时都应该调用一次,并且我需要更新每条新消息的信息。

UPD :
基于IMSoP's answer的解决方案:

<?php
require_once __DIR__ . '/../vendor/autoload.php';
use PhpAmqpLib\Connection\AMQPStreamConnection;
$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();
$channel->queue_declare('test1');
echo "[*] Waiting for messages. To exit press CTRL+C\n";
$callback = function ($msg) use ($channel) {
    list (, $cn) = $channel->queue_declare('test1', true);
    echo ' [x] Received ', $msg->body, " $cn left";
    for ($i = 0; $i < $msg->body; ++$i) {
        sleep(1);
        echo '.';
    }
    echo "\n";
};
$channel->basic_qos(null, 1, null);
$channel->basic_consume('test1', '', false, true, false, false, $callback);
while (count($channel->callbacks)) {
    $channel->wait();
}

出于某种原因总是给 0 作为消息计数。

最佳答案

queue_declare方法有一个名为“passive”的参数,可用于此目的:它仅通过名称检查队列是否存在,并忽略任何其他参数。

根据 the AMQP documentation :

If set, the server will reply with Declare-Ok if the queue already exists with the same name, and raise an error if not. The client can use this to check whether a queue exists without modifying the server state. When set, all other method fields except name and no-wait are ignored. A declare with both passive and no-wait has no effect. Arguments are compared for semantic equivalence.



请注意 Declare-Ok不仅仅是身份,而是the full response structure的名字, 带字段 queue , message-count , 和 consumer-count .

在 PHP-AMQPLib 中,您可以使用它来记录一组队列的状态,如下所示:

foreach ( $this->registeredQueues as $queueName ) {
    // The second parameter to queue_declare is $passive
    // When set to true, everything else is ignored, so need not be passed
    list($queueName, $messageCount, $consumerCount)
        = $this->rabbitChannel->queue_declare($queueName, true);

    $this->logger->info(
        "Queue $queueName has $messageCount messages and $consumerCount active consumers."
    );
}

关于php - 使用 PhpAmqpLib 从 rabbitmq 消费者的回调中获取队列大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55685418/

相关文章:

rabbitmq - 从一个 Docker 容器连接到另一个

php - 通过 Apache 在所有页面中插入 HTML 代码?

php - 获取两个mysql选择之间的值差异

windows - Windows 10 64 位上的 RabbitMQ 3.6.6 - 未检测到 Erlang

java - 如何在java中使用Iterator和MaxHeapPriorityQueue编写next方法

c - 在 C 中打印和删除队列

php - 使用 nohup 运行 Laravel 队列工作守护进程会导致 PDOException "General error: 1205 Lock wait timeout exceeded"

php - 如何在 Codeigniter 中将所有上传图像的文件名添加到数据库中?

php - 在 Netbeans 7.3 中配置 Composer

node.js - Node js 工作线程和 rabbitmq 消费者是否相同?