PHP code example of pushinbr / laravel-rabbit

1. Go to this page and download the library: Download pushinbr/laravel-rabbit 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/ */

    

pushinbr / laravel-rabbit example snippets


use App\Jobs\ProcessOrder;

ProcessOrder::dispatch($order)->onQueue('orders');

use Pushin\LaravelRabbit\Facades\LaravelRabbit;

use App\Jobs\ProcessOrder;

ProcessOrder::dispatch($order)->onQueue('orders');

'laravel_queue' => [
    'driver' => 'rabbitmq',
    'rabbit_connection' => env('LARAVEL_RABBIT_CONNECTION', 'default'),
    'queue' => env('RABBITMQ_QUEUE', 'default'),
    'exchange' => env('RABBITMQ_QUEUE_EXCHANGE', env('RABBITMQ_EXCHANGE', '')),
    'exchange_type' => env('RABBITMQ_QUEUE_EXCHANGE_TYPE', 'direct'),
    'routing_key' => env('RABBITMQ_QUEUE_ROUTING_KEY'),
    'declare' => true,
    'durable' => true,
    'delivery_mode' => 2,
    'after_commit' => false,
    'retry_after' => 90,
    'security' => [
        'sign_payloads' => false,
        'verify_payload_signatures' => false,
        'signing_key' => env('APP_KEY'),
        'invalid_signature_requeue' => false,
    ],
    'delay' => [
        'strategy' => 'ttl',
        'queue_prefix' => 'laravel.delay.',
    ],
],

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;

class ProcessOrder implements ShouldQueue
{
    use Queueable;

    public int $tries = 5;

    public int $timeout = 60;

    public function __construct(public int $orderId)
    {
    }

    public function backoff(): array
    {
        return [10, 30, 60];
    }

    public function handle(): void
    {
        // Process the order.
    }
}

ProcessOrder::dispatch($order->id)
    ->onQueue('orders')
    ->delay(now()->addMinutes(5));

use Pushin\LaravelRabbit\Facades\LaravelRabbit;

$overview = LaravelRabbit::management()->overview();
$orders = LaravelRabbit::management()->queue('orders');
$queues = LaravelRabbit::management()->queues('/');
$nodes = LaravelRabbit::management()->nodes();
$definitions = LaravelRabbit::management()->definitions();

$policies = LaravelRabbit::management()->get('/api/policies/%2F');

LaravelRabbit::management()->request('PUT', '/api/policies/%2F/ttl', body: [
    'pattern' => '^orders\\.',
    'definition' => ['message-ttl' => 60000],
    'priority' => 0,
    'apply-to' => 'queues',
]);

use Pushin\LaravelRabbit\Facades\LaravelRabbit;

LaravelRabbit::publish(
    body: 'order created',
    routingKey: 'orders.created',
    exchange: 'events',
);

use Illuminate\Support\Str;
use Pushin\LaravelRabbit\Facades\LaravelRabbit;

LaravelRabbit::publishJson(
    payload: ['order_id' => 123],
    routingKey: 'orders.created',
    exchange: 'events',
    properties: [
        'correlation_id' => (string) Str::uuid(),
        'headers' => [
            'tenant' => 'pushin',
        ],
    ],
);

use PhpAmqpLib\Message\AMQPMessage;
use Pushin\LaravelRabbit\Facades\LaravelRabbit;

LaravelRabbit::consume(function (AMQPMessage $message): void {
    $payload = json_decode($message->getBody(), true, flags: JSON_THROW_ON_ERROR);

    // Process the message.
});

use PhpAmqpLib\Message\AMQPMessage;
use Pushin\LaravelRabbit\Facades\LaravelRabbit;
use Pushin\LaravelRabbit\ValueObjects\ConsumerResult;

LaravelRabbit::consume(function (AMQPMessage $message): ConsumerResult {
    return ConsumerResult::nack(requeue: true);
});

LaravelRabbit::consume($callback, options: [
    'tag' => 'orders-worker-1',
    'wait_timeout' => 1.0,
    'idle_timeout' => 30.0,
    'max_messages' => 100,
]);

$message = LaravelRabbit::get(queue: 'orders');

if ($message !== null) {
    // Process and manually acknowledge when noAck=false.
    $message->ack();
}

LaravelRabbit::connection('analytics')->publishJson(
    payload: ['event' => 'checkout'],
    routingKey: 'analytics.checkout',
);

LaravelRabbit::publishJson(
    payload: ['event' => 'checkout'],
    routingKey: 'analytics.checkout',
    connection: 'analytics',
);

'topology' => [
    'auto_declare' => true,
    'exchanges' => [
        'events' => [
            'type' => 'topic',
            'durable' => true,
            'auto_delete' => false,
        ],
    ],
    'queues' => [
        'orders' => [
            'durable' => true,
            'arguments' => [
                'x-dead-letter-exchange' => 'events.dlx',
                'x-message-ttl' => 60000,
            ],
        ],
    ],
    'bindings' => [
        [
            'queue' => 'orders',
            'exchange' => 'events',
            'routing_key' => 'orders.*',
        ],
    ],
],

$rabbit = LaravelRabbit::connection();

$rabbit->declareExchange('events', ['type' => 'topic', 'durable' => true]);
$rabbit->declareQueue('orders', ['durable' => true]);
$rabbit->bindQueue('orders', 'events', 'orders.*');

'publisher_confirms' => [
    'enabled' => true,
    'wait' => true,
    'timeout' => 5.0,
    'wait_for_returns' => false,
],

use PhpAmqpLib\Message\AMQPMessage;

LaravelRabbit::connection()
    ->onReturned(function ($replyCode, $replyText, $exchange, $routingKey, AMQPMessage $message): void {
        report("RabbitMQ returned message: {$replyCode} {$replyText}");
    })
    ->publish('payload', options: [
        'mandatory' => true,
        'wait_for_returns' => true,
    ]);

'qos' => [
    'enabled' => true,
    'prefetch_size' => 0,
    'prefetch_count' => 10,
    'global' => false,
],

LaravelRabbit::connection()->qos(prefetchCount: 25);

'connections' => [
    'default' => [
        'user' => env('RABBITMQ_USER'),
        'password' => env('RABBITMQ_PASSWORD'),
        'vhost' => '/',
        'hosts' => [
            ['host' => 'rabbit-a.internal', 'port' => 5671],
            ['host' => 'rabbit-b.internal', 'port' => 5671],
        ],
        'ssl' => [
            'enabled' => true,
            'verify_peer' => true,
            'verify_peer_name' => true,
        ],
        'reconnect' => [
            'attempts' => 3,
            'sleep_ms' => 250,
            'multiplier' => 1.5,
        ],
    ],
],

'ssl' => [
    'enabled' => true,
    'cafile' => '/path/ca.pem',
    'capath' => null,
    'local_cert' => '/path/client.pem',
    'local_pk' => '/path/client.key',
    'passphrase' => env('RABBITMQ_SSL_PASSPHRASE'),
    'verify_peer' => true,
    'verify_peer_name' => true,
    'ciphers' => null,
    'security_level' => null,
    'crypto_method' => 'STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT',
],

'security' => [
    'tls' => false,
    'enforce_tls_peer_verification' => true,
    'forbid_guest_on_remote_hosts' => true,
    'max_message_size' => null,
],

LaravelRabbit::publishJson(
    ['order_id' => 123],
    properties: [
        'delivery_mode' => 2,
        'expiration' => '60000',
        'priority' => 5,
        'headers' => [
            'source' => 'checkout',
        ],
    ],
);
bash
php artisan vendor:publish --tag=laravel-rabbit-config
bash
php artisan rabbitmq:install
bash
php artisan queue:work --queue=orders
bash
php artisan queue:work rabbitmq --queue=orders
bash
php artisan rabbitmq:doctor
php artisan rabbitmq:stats orders
bash
php artisan rabbitmq:doctor
php artisan rabbitmq:doctor default --queue=laravel-rabbit.doctor
php artisan rabbitmq:doctor --skip-roundtrip
bash
php artisan rabbitmq:management
php artisan rabbitmq:management --queue=orders
php artisan rabbitmq:management --queues
php artisan rabbitmq:management --vhost=/
bash
php artisan rabbitmq:stats orders