Using RabbitMQ for async

Spread the love

In a previous post I spoke about using docker for setting up my dev environment. The Symfony messenger component (although IMO harder to implement that Laravel), was much easier following the flow in the book from @fabpot

First install Messenger

composer require messenger

Make your Message class. Usually this is a class in src/Message and all it does it serialize the object. The the example from @fabpot’s book, a message is put into 2 variables, so in the controller its called as:

            $context = [
                'user_ip' => $request->getClientIp(),
                'user_agent' =>$request->headers->get('user-agent'),
            $this->bus->dispatch(new CommentMessage($comment->getId(), $context));

Now, the CommentMessage simply assigned those to an object. For simplicity, lets follow his example, and I will copy the code in the next few steps:

private $id;
private $context;
public function __construct(int $id, array $context = []) {
$this->id = $id;
$this->context = $context;

public function getId(): int
return $this->id;
public function getContext(): array
return $this->context;

The logic happens in a MessageHandle, which calls an invoke, such as:

public function __invoke(CommentMessage $message)

At this point configure messenger:

            async: '%env(RABBITMQ_DSN)%'
            App\Message\YourMessageClass: async

And add RabbitMQ to your docker

image: rabbitmq:3.7-management
ports: [5672, 15672]

You are done, so just run messenger:

symfony console messenger:consume async -vv

Leave a Reply

Your email address will not be published.