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'),
                'referrer'=>$request->headers->get('referer'),
                'permalink'=>$request->getUri(),
            ];
//          
            $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:

framework:
    messenger:
        transports:
            async: '%env(RABBITMQ_DSN)%'
        routing:
            App\Message\YourMessageClass: async

And add RabbitMQ to your docker

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

You are done, so just run messenger:

symfony console messenger:consume async -vv