In order to connect Laravel with RabbitMQ we will need the following library:
composer require vladimir-yuldashev/laravel-queue-rabbitmq
thenin config/queue.php add the following configuration:
'connections' => [
// ...
'rabbitmq' => [
'driver' => 'rabbitmq',
'queue' => env('RABBITMQ_QUEUE', 'default'),
'connection' => PhpAmqpLib\Connection\AMQPLazyConnection::class,
'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' => [
'ssl_options' => [
'cafile' => env('RABBITMQ_SSL_CAFILE', null),
'local_cert' => env('RABBITMQ_SSL_LOCALCERT', null),
'local_key' => env('RABBITMQ_SSL_LOCALKEY', null),
'verify_peer' => env('RABBITMQ_SSL_VERIFY_PEER', true),
'passphrase' => env('RABBITMQ_SSL_PASSPHRASE', null),
],
'queue' => [
'job' => VladimirYuldashev\LaravelQueueRabbitMQ\Queue\Jobs\RabbitMQJob::class,
],
],
/*
* Set to "horizon" if you wish to use Laravel Horizon.
*/
'worker' => env('RABBITMQ_WORKER', 'default'),
],
// ...
],
then you need to edit the .env file, supplying your settings under the rabbitMQ section:RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_USER, RABBITMQ_PASSWORD, RABBITMQ_VHOST
also for the QUEUE_CONNECTION you should supply: rabbitmq
Now lets create a job in the terminal with:
php artisan make:job TestJob
it will handle all the incoming queue events. It's contents under /jobs:private $data;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($data)
{
//
$this->data = $data;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
print_r($this->data);
}
Finally we connect and run the created above job handler in order to handle event. Inside EventServiceProvider.phpinside the boot() function add:
$this->app->bind(
TestJob::class."@handle",
fn($job)=>{$job->handle()} // this will run the handle() function from above.
)
Then inside of a controller you can run:use App\Jobs\TestJob;
TestJob::Dispatch('hello');
you can see inside of the queue with: php artisan queue:work Cheers!
No comments:
Post a Comment