1. Go to this page and download the library: Download girni/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/ */
namespace App\Jobs\Producer;
use Girni\LaravelRabbitMQ\Message\MessageInterface;
use Girni\LaravelRabbitMQ\Producer\AbstractProducer;
class PingJobProducer extends AbstractProducer
{
public function __construct(MessageInterface $message)
{
parent::__construct($message);
}
public function name(): string
{
return 'ping:job';
}
}
namespace App\Jobs\Consumer;
use Girni\LaravelRabbitMQ\Consumer\ConsumerInterface;
class PingJobConsumer implements ConsumerInterface
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
public function producer(): string
{
return 'ping:job'; // this value must be same as Producer ::name() method we want to consume.
}
public function handle(MessageInterface $message): void
{
$key1 = $message->get('key1'); // value
$key2 = $message->get('key2'); // value2
\DB::table('test-table')->create(['key1' => $key1, 'key2' => $key2]);
}
}
/*
* You can place your custom package configuration in here.
*/
return [
'consumers' => [
\App\Jobs\Consumer\PingJobConsumer::class,
\App\Jobs\Consumer\MyTestConsumer::class
]
];
namespace App\Jobs\Consumer\Message;
use Girni\LaravelRabbitMQ\Message\MessageInterface;
class PingJobMessage implements MessageInterface
{
private string $id;
private string $name;
private Carbon $date;
public function __construct(string $id, string $name, Carbon $date)
{
$this->id = $id;
$this->name = $name;
$this->date = $date;
}
public function getId(): string
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getDate(): Carbon
{
return $this->date;
}
public static function fromArray(array $data): MessageInterface
{
return new self(
$data['id'],
$data['name'],
Carbon::createFromFormat('Y-m-d H:i:s', $data['date'])
);
}
public function toArray(): array
{
return [
'id' => $this->id,
'name' => $this->name,
'date' => $this->date
];
}
}
// consumer using the message
namespace App\Jobs\Consumer;
use Girni\LaravelRabbitMQ\Consumer\ConsumerInterface;
use Girni\LaravelRabbitMQ\Consumer\HasCustomMessage;
class PingJobConsumer implements ConsumerInterface, HasCustomMessage
{
use Dispatchable;
use InteractsWithQueue;
use Queueable;
use SerializesModels;
public function producer(): string
{
return 'ping:job';
}
/**
* @param \App\Jobs\Consumer\Message\PingJobMessage $message
* @return void
*/
public function handle(MessageInterface $message): void
{
\DB::table('test-table')->create(['name' => $message->getName(), 'date' => $message->getDate()->format('Y-m-d')]);
}
public function message(): string
{
return \App\Jobs\Consumer\Message\PingJobMessage::class;
}
}