Z
Z
Zudro2019-08-28 11:38:54
symfony
Zudro, 2019-08-28 11:38:54

How to use RabbitMqBundle in Symfony4?

What I did:
- installed Symfony 4
- installed RabbitMQ
- checked sending to and from the queue as it is written in the manual on the RabbitMQ website. Everything is working.
Next
- put RabbitMqBundle in Symfony
Created such a setting in config/old_sound_rabbit_mq.yaml

old_sound_rabbit_mq:
    connections:
        default:
            url: '%env(RABBITMQ_URL)%'
    producers:
        # use 'old_sound_rabbit_mq.task_producer' service to send data.
        task:
            connection:       default
            exchange_options: { name: 'task', type: direct }

To check, I try to send something to the queue right in the controller.
<?php

namespace App\Controller;

use App\Entity\Setting;
use App\Form\SettingType;
use App\Repository\SettingRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/setting")
 */
class SettingController extends AbstractController
{
public function edit(Request $request, Setting $setting): Response
{
    $form = $this->createForm(SettingType::class, $setting);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        //////////// Send msg to queue ////////////
            $msg = ['msg' => "Settings was changed!"];
            $this->get('old_sound_rabbit_mq.task_producer')->publish(serialize($msg));
        ////////////////////////////////////////////////

        return $this->redirectToRoute('setting_index');
    }

    return $this->render('setting/edit.html.twig', [
        'setting' => $setting,
        'form' => $form->createView(),
    ]);
}
}

I suspect that the problem is that I do not fully understand some processes in Symfony.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BoShurik, 2019-08-28
@mitrazudro

Documentation

class TaskController
{
    /**
     * @var ProducerInterface
     */
    private $producer;

    public function __construct(ProducerInterface $producer)
    {
        $this->producer = $producer;
    }

    public function indexAction($name)
    {
        $this->producer->publish('test');

        return new Response();
    }
}

# services.yaml
services:
    App\Controller\TaskController:
        arguments:
            - '@old_sound_rabbit_mq.task_producer'

or (if there is only one producer)
# services.yaml
services:
    OldSound\RabbitMqBundle\RabbitMq\ProducerInterface: '@old_sound_rabbit_mq.task_producer'

and rely on autowire
Another might come in handy: Local service binding

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question