在 RabbitMQ PHP 中设置消息优先级


Setting message priority in RabbitMQ PHP

我已经找到了很多在RabbitMQ for Java,Spring等中设置消息优先级的例子,但到目前为止,我还没有找到如何在PHP中实现这一点。

事实上,$channel->basic_publish()函数似乎不支持提供额外的参数(https://github.com/videlalvaro/php-amqplib/blob/master/PhpAmqpLib/Channel/AMQPChannel.php),即使你可以在RabbitMQ gui中执行此操作。

有没有人在PHP中使用RabbitMQ获得消息优先级?

好吧,它一直盯着我的脸。您可以在实际的message对象中设置优先级,而不是在将其推送到队列中时设置优先级:

$msg = new AMQPMessage("Hello World!", array(
    'delivery_mode' => 2,
    'priority' => 1,
    'timestamp' => time(),
    'expiration' => strval(1000 * (strtotime('+1 day midnight') - time() - 1))
));

下面是 AMQP 互操作的示例。请注意,在声明队列时,您不仅应该设置优先级标头,还应该设置一个特殊参数。

例如,安装 AMQP 互操作兼容传输

composer require enqueue/amqp-bunny

接下来要做:

<?php
use Enqueue'AmqpBunny'AmqpConnectionFactory;
use Interop'Amqp'AmqpQueue;
$context = (new AmqpConnectionFactory())->createContext(); // connects to localhost with defaults
$queue = $context->createQueue("transcode2");
$queue->addFlag(AmqpQueue::FLAG_PASSIVE);
$queue->setArgument('x-max-priority', 10);
$context->declareQueue($queue);
$message = $context->createMessage(json_encode($msg));
$message->setPriority(5);
$producer = $context->createProducer($queue, $message);
$producer->send($queue, $message);