PHP code example of jaapieaapie1 / rabbitmq-ext

1. Go to this page and download the library: Download jaapieaapie1/rabbitmq-ext 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/ */

    

jaapieaapie1 / rabbitmq-ext example snippets


use RabbitMQ\Connection;

$connection = new Connection('amqp://guest:guest@localhost:5672');
$consumer = $connection->consume('my-queue', prefetchCount: 50);

$consumer->each(function ($message) {
    echo $message->getBody() . PHP_EOL;

    $message->ack();

    return true; // return false to stop consuming
});

$connection->close();

$consumer = $connection->consume('my-queue');

while ($message = $consumer->next(timeoutMs: 5000)) {
    echo $message->getRoutingKey() . ': ' . $message->getBody() . PHP_EOL;
    $message->ack();
}

// null returned — timed out or consumer was cancelled
$connection->close();

$connection = new Connection('amqp://guest:guest@localhost:5672');

// Publish and wait for broker confirmation
$connection->publish('my-exchange', 'routing.key', '{"event":"order.created"}', [
    'x-request-id' => 'abc-123',
]);

// Fire-and-forget (confirmed before connection closes)
$connection->publishAsync('my-exchange', 'routing.key', 'payload');

$connection->close();

$consumer = $connection->consume('my-queue');

$consumer->each(function ($message) {
    try {
        processMessage($message->getBody());
        $message->ack();
    } catch (\Throwable $e) {
        $message->nack(requeue: false); // dead-letter the message
    }

    return true;
});