Backend Development 3 min read

Implementing a Producer‑Consumer Model with RabbitMQ in PHP

This tutorial explains the producer‑consumer principle using RabbitMQ, provides a reusable PHP base class for queue connections, and demonstrates how to create service and client classes to send and receive messages, followed by step‑by‑step instructions to run the code and view the queue.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Implementing a Producer‑Consumer Model with RabbitMQ in PHP

1. Principle: The producer ("P") sends messages to a RabbitMQ queue, which acts as a buffer, and the consumer ("C") retrieves messages from that queue.

2. 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();
    }
}

3. Define the service (server) class that extends the common base:

namespace app\admin\controller\mq_queue;

use PhpAmqpLib\Message\AMQPMessage;

class Server extends Common {
    public $message = 'I am Hello Queue';
    public function sendMessage() {
        // Declare the queue
        $this->channel->queue_declare($this->queue, false, false, false, false);
        $msg = new AMQPMessage($this->message);
        // Publish the message
        $this->channel->basic_publish($msg, '', $this->queue);
        echo "ok";
    }
}

4. Define the client class that also extends the common base and consumes messages:

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();
        }
    }
}

5. Run the code:

Request the server route; the queue already contains data.

View detailed queue information (screenshots shown in the original article).

Request the client route to retrieve all messages from the queue.

The article also includes several illustrative images showing the queue diagram, request results, and prompts encouraging readers to like and share the content.

backend developmentMessage QueueRabbitMQPHPproducer-consumer
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.