Symfony 4 and RabbitMQ

Mert Sevinc
Apr 2, 2018 · 4 min read
rabbitmqctl add_vhost my_project
rabbitmqctl set_permissions -p my_project my_username ".*" ".*" ".*"
composer create-project symfony/skeleton my-project
composer require php-amqplib/rabbitmq-bundle
OldSound\RabbitMqBundle\OldSoundRabbitMqBundle::class => ['all' => true]
parameters:
rabbitmq_host: 'localhost'
rabbitmq_user: 'my_username'
rabbitmq_password: 'my_password'
rabbitmq_statuslayer_vhost: 'my_project'
email_service:
class:
App\Rabbit\EmailService

old_sound_rabbit_mq:
connections:
default:
host: '%rabbitmq_host%'
user: '%rabbitmq_user%'
password: '%rabbitmq_password%'
vhost: '%rabbitmq_my_project_vhost%'
producers:
emailing:
connection:
default
exchange_options:
name:
emails
type: direct
consumers:
emailing:
connection:
default
exchange_options: {name: 'emails', type: direct}
queue_options: {name: 'emails'}
callback: email_service
php bin/console rabbitmq:setup-fabric
/**
*
@Route("/createUser")
*
@Method("POST")
*/
public function postCreateUser(Request $request)
{

$message = ["Type"=>"VerificationEmail","Firstname"=>$request->get('firstname'),"Lastname"=>$request->get('lastname'),"Email"=>$request->get('email')];
$rabbitMessage = json_encode($message);

$this->get('old_sound_rabbit_mq.emailing_producer')->setContentType('application/json');
$this->get('old_sound_rabbit_mq.emailing_producer')->publish($rabbitMessage);

return new JsonResponse(array('Status' => 'OK'));

}
<?php
namespace
App\Rabbit;

use OldSound\RabbitMqBundle\RabbitMq\ConsumerInterface;
use PhpAmqpLib\Message\AMQPMessage;

class EmailService implements ConsumerInterface
{

public function execute(AMQPMessage $msg)
{

$body = $msg->body;
//var_dump($body);

$response = json_decode($msg->body, true);

$type = $response["Type"];

if ($type == "VerificationEmail") $this->sendVerificationEmail($response);
}

private function sendVerificationEmail($response) {

// do something
}
}
php bin/console rabbitmq:consumer emailing

Mert Sevinc

Written by

https://www.linkedin.com/in/mertsevinc/

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade