Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a producer as a service into a RabbitMQBundle consumer?

I have to modify a php system developed with Symfony and RabbitMQ as a queing system. I'm not directly using the RabbitMQ bindings with PHP, but the RabbitMQBundle for Symfony.

My problem is that I don't know how to publish a message from a consumer. Yes, I know, a consumer is designed to consume messages, not to publish messages. But I have a multi-step workflow, and I need to publish new messages after some previous messages are processed.

The "magic" of Symfony is making me impossible to discovering how is wired everything. I've been reading about services, but as far as I know, the "producers" aren't declared as services anywhere, and in my particular case I'm not using specific classes for everyone, but only binding a name to a RabbitMq exchange.

In my controllers is easy to call those producers, I only have to type something like

$this->get('old_sound_rabbit_mq.my_own_producer')->publish($whatever);

but in consumers I have to explicitly inject every dependency, and I don't know how to inject the producer.

The declaration of my producer in the rabbitmqbundle settings is something like this:

my_own:
        connection:       default
        exchange_options: {name: 'my-own-channel', type: direct}

The declaration of my consumer service in the services.yml file is something like:

my_own_service:
    class: MyOwnBundleBundle\Consumers\MyOwnConsumer
    arguments: ["@logger", "@doctrine_mongodb", "%variable1%", "%variable2%"]
    tags:
        - { name: monolog.logger, channel: my_own_channel }

Thank you for your time.

like image 838
castarco Avatar asked Jul 29 '15 09:07

castarco


1 Answers

You can inject the rabbitmq producer in your consumer and use it as usual. As example you can change the consumer service configuration as follow (see the last arguments):

my_own_service:
    class: MyOwnBundleBundle\Consumers\MyOwnConsumer
    arguments: ["@logger", "@doctrine_mongodb", "%variable1%", "%variable2%", "@old_sound_rabbit_mq.another_producer"]
    tags:
        - { name: monolog.logger, channel: my_own_channel }

and change the contructor of your service to accept the new parameter:

protected $producer;

public function __construct($logger, $doctrine, $var1,$var2, $producer)
{
    ...
    $this->producer=$producer;
}

And so use it as :

public function execute(AMQPMessage $msg)
    {
       ....
       $mesassage = ....

      $this->producer-> publish($message);

    }

Hope this help

like image 90
Matteo Avatar answered Oct 15 '22 04:10

Matteo