From RabbitMqBundle to PhpEnqueue via Symfony Messenger

Today i try to explain how i migrate from RabbitMqBundle to PhpEnqueue using the Messenger component of Symfony.

Stack

  • PHP 7.2
  • Symfony 4.1

Starting Situation

I have well installed RabbitMQ following simple tutorial Symfony 4 and RabbitMQ.

So in my configuration file i have the following configuration:

#config/packages/old_sound_rabbit_mq.yaml
old_sound_rabbit_mq:
enable_collector: false
connections:
default:
url: '%env(RABBITMQ_URL)%'
lazy: true
    producers:
mailer:
connection: default
exchange_options:
name: mailer
type: direct
consumers:
mailer:
connection: default
exchange_options: {name: 'mailer', type: direct}
queue_options: {name: 'mailer'}
callback: App\Consumer\Mailer\MailerConsumer

And i have my producer service:

<?php
namespace App\Service\Mailer;
use OldSound\RabbitMqBundle\RabbitMq\ProducerInterface;
class MailerProducerService
{
/**
* @var ProducerInterface
*/
private $producer;
    /**
* MailerProducerService constructor.
*
* @param ProducerInterface $producer
*/
public function __construct(ProducerInterface $producer)
{
$this->producer = $producer;
}
    /**
* @param array $data
*/
public function send(array $data)
{
$this->producer->publish(json_encode('data' => $data));
}
}

And my consumer

<?php
namespace App\Consumer\Mailer;
use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;
use Psr\Log\LoggerInterface;
class MailerConsumer implements ConsumerInterface
{
private $logger;
    public function __construct(LoggerInterface $logger) 
{
$this->logger = $logger;
}
    public function execute(AMQPMessage $msg)
{
$data = json_decode($msg->getBody(), true);

// Do something with the message received
...
...
}
}

Continue reading to original source: https://stefanoalletti.wordpress.com/2018/11/05/from-rabbitmq-to-phpenqueue-via-symfony-messenger/