PHP code example of mjohann / simple-rabbitmq

1. Go to this page and download the library: Download mjohann/simple-rabbitmq library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mjohann / simple-rabbitmq example snippets




use MJohann\Packlib\SimpleRabbitMQ;

ion
$srmq = new SimpleRabbitMQ();

// Open the connection to the RabbitMQ server
$srmq->open();

// Declare an exchange named "my_exchange"
$srmq->exchange("my_exchange");

// Declare a queue named "my_queue"
$srmq->queue("my_queue");

// Bind the declared queue to the exchange
$srmq->queueBind();

// Publish 30,000 messages to the exchange
for ($i = 1; $i <= 30000; $i++) {
    $srmq->pubExchange("test " . $i); // Publish a message with a test string
    echo $i, PHP_EOL; // Output the message number to the console
}

// Close the connection to the RabbitMQ server
$srmq->close();




use MJohann\Packlib\SimpleRabbitMQ;

ion
$srmq = new SimpleRabbitMQ();

// Open the connection to the RabbitMQ server
$srmq->open();

// Declare an exchange named "my_exchange"
$srmq->exchange("my_exchange");

// Declare a queue named "my_queue"
$srmq->queue("my_queue");

// Bind the declared queue to the exchange
$srmq->queueBind();

// Define the first callback function to handle incoming messages
$callback = function ($message, $consumer) {
    echo "Message: ", $message->getBody(), PHP_EOL; // Print the message content
    $consumer->acknowledge($message); // Acknowledge the message to RabbitMQ
    return true; // Return true to continue listening
};

// Subscribe the first callback to the queue
$srmq->sub($callback);

// Optionally, read a single message manually (commented out)
// $srmq->readMessage();

// Wait for messages and trigger callbacks for up to 15 seconds
$srmq->waitCallbacks(15000); // 15000 milliseconds = 15 seconds

// Close the connection to the RabbitMQ server
$srmq->close();

simple-rabbitmq/
├── src/
│   └── SimpleRabbitMQ.php
│   └── Facades/
│       └── SimpleRabbitMQ.php
├── example/
│   └── docker-compose.php
│   └── sub.php
│   └── pub.php
├── composer.json
├── .gitignore
├── LICENSE
└── README.md