Hion Coding - Blogs share everything
  • HOME
  • ABOUT
  • POSTS
  • CONTACT
  • TOOLS
    CÂU HỎI VÕ ĐÀI TỐI THƯỢNG CONVERT IMAGE TO WEBP
Integrating RabbitMQ with PHP

Integrating RabbitMQ with PHP

Hion Coding - Blogs share everything
Admin Hion Coding Blogs vochilong.work@gmail.com
9th April 2024

PHP/Laravel

Integrating RabbitMQ with PHP

RabbitMQ, a powerful message broker, offers a seamless solution for PHP developers to decouple components, distribute tasks, and enhance communication within their applications.

This comprehensive guide takes you on a journey into the integration of RabbitMQ with PHP, providing step-by-step examples for both sending and receiving messages. By the end, you'll have a deep understanding of how RabbitMQ can empower your PHP applications.
 

Understanding RabbitMQ

Before we dive into the code, let's grasp the essence of RabbitMQ and why it's a game-changer for developers.

RabbitMQ serves as a message broker, acting as an intermediary for message exchange between different parts of an application. It enables efficient distribution of tasks, decoupling of components, and seamless communication among microservices or various parts of a monolithic application.

Getting Started: Installation and Setup

Step 1: Install RabbitMQ

Begin by installing RabbitMQ on your server. You can find installation instructions for different platforms on the official RabbitMQ website.

Step 2: Set Up a Connection

To interact with RabbitMQ from your PHP application, you'll need the php-amqplib library. Install it using Composer:

composer require php-amqplib/php-amqplib

Sending a Message with PHP

Step 3: Publish a Message

Let's start with sending a message to a RabbitMQ queue. Here's a PHP code example:
 

require_once __DIR__ . '/vendor/autoload.php';

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

$connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
$channel = $connection->channel();

$channel->queue_declare('hello', false, false, false, false);

$messageBody = 'Hello, RabbitMQ!';
$message = new AMQPMessage($messageBody);

$channel->basic_publish($message, '', 'hello');

echo " [x] Sent '$messageBody'\n";

$channel->close();
$connection->close();

In this example, we connect to the RabbitMQ server, declare a queue named 'hello,' create a message, and publish it to the queue.

Receiving a Message with PHP

Step 4: Consume a Message

Now, let's set up the PHP code to consume messages from the queue:
 

<?php
use PhpAmqpLib\Connection\AMQPStreamConnection;

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

$connection = new AMQPStreamConnection($AMQP);
$channel = $connection->channel();

$channel->queue_declare('hello', false, false, false, false);

$callback = function($message) {
   echo ' [*] Receiver ' . $message->body;
};

$channel->basic_consume('hello', '', false, true, false, false, $callback);

while(count($channel->callbacks)) {
    $channel->wait();
}

$channel->close();
$connection->close();

This code establishes a callback function to process incoming messages and enters a loop to wait for messages.
If you want RabbitMQ and PHP to return tasks back to the queue when the handle message has an exception
set the auto no_ack flag to false in function basic_consume()

queue: Queue from where to get the messages
consumer_tag: Consumer identifier
no_local: Don't receive messages published by this consumer.
no_ack: Tells the server if the consumer will acknowledge the messages.
exclusive: Request exclusive consumer access, meaning only this consumer can access the queue
nowait:
callback: A PHP Callback

<?php
use PhpAmqpLib\Connection\AMQPStreamConnection;

echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";

$connection = new AMQPStreamConnection($AMQP);
$channel = $connection->channel();

$channel->queue_declare('hello', false, false, false, false);

$callback = function($message) {
    try {
        //handle in here
        // basic_ack: confirm handle success to RabbitMQ -> RabbitMQ delete message queue
        $message->basic_ack($message->delivery_info['delivery_tag']);
    } catch (\Exception $e) {
        // basic_nack: confirm handle fail to RabbitMQ -> RabbitMQ retry message queue 
        //if you set true requeue in basic_nack -> RabbitMQ retry message 
        //esle you set false param requeue in basic_nack -> RabbitMQ hold message a period of time
        $message->basic_nack($message->delivery_info['delivery_tag'], false, true);
    }
};

$channel->basic_consume('hello', '', false, false, false, false, $callback);

while(count($channel->callbacks)) {
    $channel->wait();
}

$channel->close();
$connection->close();

Conclusion

RabbitMQ excels in message queuing, distribution, and communication between various parts of your application, leading to improved performance, scalability, and reliability.

As you delve deeper into RabbitMQ, you'll discover advanced features such as message acknowledgments, routing, and exchanges that allow you to tailor your messaging system to your application's unique requirements.

With RabbitMQ and PHP, you're well-prepared to build resilient, scalable, and responsive applications that handle messaging seamlessly.

Thank you !!! Good luck !!! Hion Coding


Integrating CKEditor 5 In Laravel 10 Using Vite

9th April 2024

Integrating CKEditor 5 In Laravel 10 Using Vite

PHP/Laravel

Laravel Eloquent Tips🔥 🚀

3rd January 2024

Laravel Eloquent Tips🔥 🚀

PHP/Laravel

Elevating Junior Laravel Developers: Learn about Contract

3rd January 2024

Elevating Junior Laravel Developers: Learn about Contract

PHP/Laravel

Elevating Junior Laravel Developers: Learn about Service Provider

3rd January 2024

Elevating Junior Laravel Developers: Learn about Service Provider

PHP/Laravel

Hion Coding - Blogs share everything


© 2025 Hion Coding DMCA.com Protection Status