Backend Development 3 min read

Implementing Priority Queues with RabbitMQ in PHP

This article explains how to configure RabbitMQ queue priority, defines reusable PHP base, service, and client classes, and demonstrates running the code to send and consume prioritized messages using the PhpAmqpLib library.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Implementing Priority Queues with RabbitMQ in PHP

Overview: The article describes setting the maximum priority for a RabbitMQ queue (up to 255, but the official recommendation is 1‑10) and notes that higher values increase memory and CPU usage.

Define a common base class:

namespace app\admin\controller\mq_queue;
use PhpAmqpLib\Connection\AMQPStreamConnection;
class Common {
    public $queue = 'hello';
    public $channel;
    public function __construct() {
        $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest', '/');
        $this->channel = $connection->channel();
    }
}

Define the service class:

namespace app\admin\controller\mq_queue;
use PhpAmqpLib\Message\AMQPMessage;
class Server extends Common {
    public $message = 'I am Hello Queue';
    public function sendMessage() {
        // 设置优先级
        $param['x-max-priority'] = 8;
        // 直接使用队列
        $this->channel->queue_declare($this->queue, false, false, false, false, false, $param);
        $msg = new AMQPMessage($this->message);
        // 发送消息
        $this->channel->basic_publish($msg, '', $this->queue);
        echo "ok";
    }
}

Define the client class:

namespace app\admin\controller\mq_queue;
use PhpAmqpLib\Message\AMQPMessage;
class Client extends Common {
    public function getMessage() {
        $channel = $this->channel;
        $this->channel->basic_consume($this->queue, '', false, true, false, false, function (AMQPMessage $msg) use ($channel) {
            var_dump($msg->body);
        });
        while ($channel->is_open()) {
            $channel->wait();
        }
    }
}

Running the code: 1) Request the server route; the queue already contains data. 2) View detailed queue information. Screenshots are provided to illustrate the request result and the queue details.

The article concludes by encouraging readers to like and share if they found the tutorial helpful.

backend developmentMessage QueueRabbitMQPriority QueuePHP
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.