PHP code example of batatahub-tech / laravel-rabbitmq
1. Go to this page and download the library: Download batatahub-tech/laravel-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/ */
batatahub-tech / laravel-rabbitmq example snippets
namespace App\RabbitMQ\Consumers;
use PhpAmqpLib\Message\AMQPMessage;
class UserCreatedConsumer
{
public function handle(AMQPMessage $message): void
{
try {
$payload = json_decode($message->getBody(), true);
// Process your payload...
// Confirm to the broker that processing succeeded
$message->ack();
} catch (\Throwable $e) {
// Reject; requeue=true. Adjust to your retry policy.
$message->nack(false, true);
throw $e;
}
}
}
use BatataHub\RabbitMQ\Services\RabbitMQService;
class UserController
{
public function store(RabbitMQService $rabbit)
{
// Setup topology if needed
$rabbit
->declareExchange('users', 'topic')
->declareQueue('UserCreatedQueue')
->bindQueue('UserCreatedQueue', 'users', 'user.created')
// Publish payload to the exchange with routing key
->publish('users', 'user.created', [
'id' => 123,
'name' => 'Jane',
]);
// ...
}
}
use BatataHub\RabbitMQ\Services\RabbitMQService;
use PhpAmqpLib\Message\AMQPMessage;
class Worker
{
public function __invoke(RabbitMQService $rabbit): void
{
$rabbit->consume('UserCreatedQueue', function (AMQPMessage $message) {
$data = json_decode($message->getBody(), true);
// ... process ...
$message->ack();
});
$rabbit->startConsuming();
}
}