PHP code example of almatar / rabbitmq

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

    

almatar / rabbitmq example snippets




return [
    'connections' => [
        'default' => [
            'host' => 'localhost',
            'port' => 5672,
            'user' => 'guest',
            'password' => 'password',
            'vhost' => '/',
            'connection_attempts' => 10,
            'reconnect_waiting_seconds' => 3,
            'read_write_timeout' => 30, // heartbeat * 2 at least
            'heartbeat' => 15,
        ],
    ],
    'producers' => [
        'test_producer' => [
            'exchange_options' => [
                'name' => 'test_exchange',
                'type' => 'fanout'
            ],
            'queue_options' => [
                'name' => 'test_queue',
                'routing_key' => '',
            ]
        ]
    ],
    'consumers' => [
        'test_consumer' => [
            'qos_prefetch_count' => 5,
            'exchange_options' => [
                'name' => 'test_exchange',
                'type' => 'fanout'
            ],
            'queue_options' => [
                'name' => 'test_queue',
                'routing_key' => '',
            ]
        ]
    ],
];


$app->configure('rabbitmq');

$app->register(Almatar\RabbitMQ\RabbitMQServiceProvider::class);



namespace App\Console\Commands;

use Throwable;
use Illuminate\Console\Command;
use PhpAmqpLib\Message\AMQPMessage;
use Almatar\RabbitMQ\Adapters\Consumer;

class TestConsumer extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:consumer';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test rabbitmq consumer';

    /**
     *
     * @var Consumer
     */
    private $consumer;

    /**
     * TestCommand constructor.
     * @param Consumer $consumer
     * @param TestService $service
     */
    public function __construct(Consumer $consumer)
    {
        $this->consumer = $consumer;
        parent::__construct();
    }

    /**
     * @throws \Exception
     */
    public function handle()
    {
        $this->info('[x] Test rabbitmq command consumer is up');
        
        $this->consumer->subscribe(
            config('rabbitmq.consumers.test_consumer'),
            [$this, 'consume']
        );
    }

    public function consume(AMQPMessage $message)
    {
        try {
            $this->info('Message Consumed'); $this->info($message->getBody());
            $message->ack();
        } catch (Throwable $t) {
            die($t->getMessage());
        }
    }
}





namespace App\Services;

use Almatar\RabbitMQ\Adapters\Producer;

class TestService
{
    /**
     * @var Producer
     */
    private $producer;

    /**
     * TestService constructor.
     * @param Producer $producer
     */
    public function __construct(Producer $producer)
    {
        $this->producer = $producer;
    }

    /**
     * @param AMQPMessage $message
     * @throws Exception
     */
    public function execute()
    {
        $testMessageBody = [
            'name' => 'John Doe',
            'Age' => 7000
        ];

        $messageBody = json_encode($testMessageBody);

        $this->producer->publish(
            config('rabbitmq.producers.test_producer'), 
            $messageBody
        );
    }
}


'connections' => [
    // ... other connections
    'rabbitmq' => [
        'driver' => 'rabbitmq',
        'hosts' => [
            [
                'host' => env('RABBITMQ_HOST', '127.0.0.1'),
                'port' => env('RABBITMQ_PORT', 5672),
                'user' => env('RABBITMQ_USER', 'guest'),
                'password' => env('RABBITMQ_PASSWORD', 'guest'),
                'vhost' => env('RABBITMQ_VHOST', '/'),
            ],
        ],
        'options' => [
            'exchange' => [
                'name' => env('RABBITMQ_EXCHANGE_NAME', 'default'),
                'type' => env('RABBITMQ_EXCHANGE_TYPE', 'direct'),
                'declare' => env('RABBITMQ_EXCHANGE_DECLARE', true),
                'passive' => env('RABBITMQ_EXCHANGE_PASSIVE', false),
                'durable' => env('RABBITMQ_EXCHANGE_DURABLE', true),
                'auto_delete' => env('RABBITMQ_EXCHANGE_AUTODELETE', false),
                'internal' => env('RABBITMQ_EXCHANGE_INTERNAL', false),
                'nowait' => env('RABBITMQ_EXCHANGE_NOWAIT', false),
            ],
            'queue' => [
                'declare' => env('RABBITMQ_QUEUE_DECLARE', true),
                'passive' => env('RABBITMQ_QUEUE_PASSIVE', false),
                'durable' => env('RABBITMQ_QUEUE_DURABLE', true),
                'exclusive' => env('RABBITMQ_QUEUE_EXCLUSIVE', false),
                'auto_delete' => env('RABBITMQ_QUEUE_AUTODELETE', false),
                'bind' => env('RABBITMQ_QUEUE_BIND', true),
                'routing_key' => env('RABBITMQ_QUEUE_ROUTING_KEY', ''),
            ],
        ],
    ],
],

use Almatar\RabbitMQ\Adapters\Producer;

class TestService
{
    public function execute()
    {
        $producer = app(Producer::class);
        $producer->publish(
            config('rabbitmq.producers.test_producer'), 
            json_encode(['name' => 'John Doe', 'Age' => 7000])
        );
    }
}

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessMessageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;

    public function __construct(array $data)
    {
        $this->data = $data;
    }

    public function handle()
    {
        // Your message processing logic here
        Log::info('Processing message', $this->data);
    }
}

// Dispatch the job
ProcessMessageJob::dispatch(['name' => 'John Doe', 'Age' => 7000]);

use Almatar\RabbitMQ\Adapters\Consumer;

class TestConsumer extends Command
{
    public function handle()
    {
        $consumer = app(Consumer::class);
        $consumer->subscribe(
            config('rabbitmq.consumers.test_consumer'),
            [$this, 'consume']
        );
    }

    public function consume(AMQPMessage $message)
    {
        $this->info('Message Consumed: ' . $message->getBody());
        $message->ack();
    }
}