Setting message priority in RabbitMQ PHP

3.7k views Asked by At

I've found plenty of examples of setting message priority in RabbitMQ for Java, Spring, etc. but so far I haven't found how to implement this in PHP.

In fact the $channel->basic_publish() function doesn't appear to support supplying additional parameters (https://github.com/videlalvaro/php-amqplib/blob/master/PhpAmqpLib/Channel/AMQPChannel.php), even though you can do this in the RabbitMQ gui.

Has anyone got message priorities working with RabbitMQ in PHP?

2

There are 2 answers

0
user101289 On BEST ANSWER

OK, it was staring me in the face the whole time. You set the priority in the actual message object, not when you push it into the queue:

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

Here's an example for AMQP Interop. Pay attention that you should not only set a priority header but a special argument while declaring a queue.

Install AMQP Interop compatible transport, for example

composer require enqueue/amqp-bunny

And do next:

<?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);