@mitrazudro
php jun

Как использовать RabbitMqBundle в Symfony4?

Что сделал:
- поставил Symfony 4
- поставил RabbitMQ
- проверил отправку в очередь и из неё как написано в мануале на сайте RabbitMQ. Всё работает.
Дальше
- поставил RabbitMqBundle в Symfony

Создал такую настроку в 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 }


Для проверки пробую отправить что то в очередь прям в контроллере.

<?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(),
    ]);
}
}


Подозреваю, что проблема в том что я не до конца понимаю каких то процессов в Symfony.

Что я делаю не так?
  • Вопрос задан
  • 1054 просмотра
Решения вопроса 1
BoShurik
@BoShurik Куратор тега Symfony
Symfony developer
Документация
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'

либо (если producer только одни)
# services.yaml
services:
    OldSound\RabbitMqBundle\RabbitMq\ProducerInterface: '@old_sound_rabbit_mq.task_producer'

и понадеяться на autowire
Еще может пригодится: Local service binding
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы