54
loading...
This website collects cookies to deliver better user experience
symfony new --full php-symfony-rabbitmq
symfony serve
composer require symfony/messenger
final class SampleMessage
{
public function __construct(private string $content)
{
}
public function getContent(): string
{
return $this->content;
}
}
final class SampleMessangeHandler implements MessageHandlerInterface
{
public function __invoke(SampleMessage $message)
{
// magically invoked when an instance of SampleMessage is dispatched
print_r('Handler handled the message!');
}
}
final class SampleController extends AbstractController
{
#[Route('/sample', name: 'sample')]
public function sample(MessageBusInterface $bus): Response
{
$message = new SampleMessage('content');
$bus->dispatch($message);
return new Response(sprintf('Message with content %s was published', $message->getContent()));
}
}
curl http://localhost:8000/sample
Handler handled the message!Message with content content was published
.docker-compose.yml
file on the project root directory to add a new service:version: '3'
services:
rabbitmq:
image: rabbitmq:3.9-management
ports:
- '5672:5672'
- '15672:15672'
docker-compose up
on project root directory, I can see everything is working./bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
rabbitmq-c
:brew install rabbitmq-c
pecl install amqp
librabbitmq
, you need to check which version is installed inside the folder /usr/local/Cellar/rabbitmq-c/
. Mine was 0.11.0
:Set the path to librabbitmq install prefix [autodetect] : /usr/local/Cellar/rabbitmq-c/0.11.0
composer require symfony/amqp-messenger
guest
, which is coincidentally the exact line I need to uncomment on .env
file to expose the RabbitMQ connection as an environment variable:###> symfony/messenger ###
# Choose one of the transports below
# MESSENGER_TRANSPORT_DSN=doctrine://default
MESSENGER_TRANSPORT_DSN=amqp://guest:guest@localhost:5672/%2f/messages
# MESSENGER_TRANSPORT_DSN=redis://localhost:6379/messages
###< symfony/messenger ###
config/packages/messanger.yaml
, I defined a new transport and the message type that will use it:framework:
messenger:
transports:
# https://symfony.com/doc/current/messenger.html#transport-configuration
async: '%env(MESSENGER_TRANSPORT_DSN)%'
routing:
# Route your messages to the transports
'App\Message\SampleMessage': async
curl http://localhost:8000/sample
php bin/console messenger:consume async -vv
[messenger] Received message App\Message\SampleMessage
[messenger] App\Message\SampleMessage was handled successfully (acknowledging to transport).
[messenger] Message App\Message\SampleMessage handled by App\MessageHandler\SampleMessangeHandler