composer require php-amqplib/php-amqplib
2.RabbitMQ paketini .env üzerinde yapılandırma:RABBITMQ_HOST=your_rabbitmq_host
RABBITMQ_PORT=your_rabbitmq_port
RABBITMQ_VHOST=your_rabbitmq_vhost
RABBITMQ_LOGIN=your_rabbitmq_login
RABBITMQ_PASSWORD=your_rabbitmq_password
<?php
namespace App;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
class RabbitMQService
{
protected $connection;
protected $channel;
protected $exchange = 'your_exchange_name';
protected $queue = 'your_queue_name';
protected $routingKey = 'your_routing_key';
public function __construct()
{
$this->connection = new AMQPStreamConnection(
env('RABBITMQ_HOST'),
env('RABBITMQ_PORT'),
env('RABBITMQ_LOGIN'),
env('RABBITMQ_PASSWORD'),
env('RABBITMQ_VHOST')
);
$this->channel = $this->connection->channel();
$this->channel->exchange_declare($this->exchange, 'direct', false, true, false);
$this->channel->queue_declare($this->queue, false, true, false, false);
$this->channel->queue_bind($this->queue, $this->exchange, $this->routingKey);
}
public function publish($message)
{
$msg = new AMQPMessage($message);
$this->channel->basic_publish($msg, $this->exchange, $this->routingKey);
}
public function consume($callback)
{
$this->channel->basic_consume($this->queue, '', false, true, false, false, $callback);
while ($this->channel->is_consuming()) {
$this->channel->wait();
}
}
public function __destruct()
{
$this->channel->close();
$this->connection->close();
}
}
<?php
namespace App\Http\Controllers;
use App\RabbitMQService;
use Illuminate\Http\Request;
class RabbitMQController extends Controller
{
public function publishMessage(Request $request)
{
$message = $request->input('message');
$rabbitMQService = new RabbitMQService();
$rabbitMQService->publish($message);
return response('Message published to RabbitMQ');
}
public function consumeMessage()
{
$rabbitMQService = new RabbitMQService();
$callback = function ($msg) {
echo "Received message: " . $msg->body . "\n";
};
$rabbitMQService->consume($callback);
}
}
Route::post('/publish', 'RabbitMQController@publishMessage');
Route::get('/consume', 'RabbitMQController@consumeMessage');
Laravele RabbitMQ kurulumu işte bu kadar kolay artık tanımladığımız routelar ile işlemlerimizi RabbitMQ ile paylaşabilir ve mesajların durumlarını consume route'u ile dinleyebiliriz.