PHPackages                             wanupsml/rabbitmq-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. wanupsml/rabbitmq-bundle

ActiveSymfony-bundle[Queues &amp; Workers](/categories/queues)

wanupsml/rabbitmq-bundle
========================

Integrates php-amqplib with Symfony2 and RabbitMq

1.8.164102(9y ago)04.5kMITPHPPHP &gt;=5.5

Since Jan 18Pushed 9y ago4 watchersCompare

[ Source](https://github.com/wanupclub/RabbitMqBundle)[ Packagist](https://packagist.org/packages/wanupsml/rabbitmq-bundle)[ Docs](https://github.com/wanupsml/RabbitMqBundle/)[ RSS](/packages/wanupsml-rabbitmq-bundle/feed)WikiDiscussions master Synced 4w ago

READMEChangelogDependencies (9)Versions (23)Used By (0)

RabbitMqBundle
==============

[](#rabbitmqbundle)

\[!\[Latest Version on Packagist\]\[ico-version\]\]\[link-packagist\] [![SensioLabsInsight](https://camo.githubusercontent.com/11151cf3d222c98317df4fa2808d846fb613c8e9395a89fbce2efff6654191f1/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f34663836316566652d336537322d346439652d396433312d3532663238313864366538382f6d696e692e706e67)](https://insight.sensiolabs.com/projects/4f861efe-3e72-4d9e-9d31-52f2818d6e88)\[!\[Build Status\]\[ico-travis\]\]\[link-travis\]

About
-----

[](#about)

The RabbitMqBundle incorporates messaging in your application via [RabbitMQ](http://www.rabbitmq.com/) using the [php-amqplib](http://github.com/videlalvaro/php-amqplib) library.

The bundle implements several messaging patterns as seen on the [Thumper](https://github.com/videlalvaro/Thumper) library. Therefore publishing messages to RabbitMQ from a Symfony2 controller is as easy as:

```
$msg = array('user_id' => 1235, 'image_path' => '/path/to/new/pic.png');
$this->get('wanup_sml_rabbit_mq.upload_picture_producer')->publish(serialize($msg));
```

Later when you want to consume 50 messages out of the `upload_pictures` queue, you just run on the CLI:

```
$ ./app/console rabbitmq:consumer -m 50 upload_picture
```

All the examples expect a running RabbitMQ server.

This bundle was presented at [Symfony Live Paris 2011](http://www.symfony-live.com/paris/schedule#session-av1) conference. See the slides [here](http://www.slideshare.net/wanup_sml/theres-a-rabbit-on-my-symfony).

Installation
------------

[](#installation)

### For Symfony Framework &gt;= 2.3

[](#for-symfony-framework--23)

Require the bundle and its dependencies with composer:

```
$ composer require WanupSml/rabbitmq-bundle
```

Register the bundle:

```
// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        new WanupSml\RabbitMqBundle\WanupSmlRabbitMqBundle(),
    );
}
```

Enjoy !

### For a console application that uses Symfony Console, Dependency Injection and Config components

[](#for-a-console-application-that-uses-symfony-console-dependency-injection-and-config-components)

If you have a console application used to run RabbitMQ consumers, you do not need Symfony HttpKernel and FrameworkBundle. From version 1.6, you can use the Dependency Injection component to load this bundle configuration and services, and then use the consumer command.

Require the bundle in your composer.json file:

```
{
    "require": {
        "WanupSml/rabbitmq-bundle": "~1.6",
    }
}
```

Register the extension and the compiler pass:

```php
use WanupSml\RabbitMqBundle\DependencyInjection\WanupSmlRabbitMqExtension;
use WanupSml\RabbitMqBundle\DependencyInjection\Compiler\RegisterPartsPass;

// ...

$containerBuilder->registerExtension(new WanupSmlRabbitMqExtension());
$containerBuilder->addCompilerPass(new RegisterPartsPass());
```

### Warning - BC Breaking Changes ###

* Since 2012-06-04 Some default options for exchanges declared in the "producers" config section
  have changed to match the defaults of exchanges declared in the "consumers" section.
  The affected settings are:

  * `durable` was changed from `false` to `true`,
  * `auto_delete` was changed from `true` to `false`.

  Your configuration must be updated if you were relying on the previous default values.
* Since 2012-04-24 The ConsumerInterface::execute method signature has changed
* Since 2012-01-03 the consumers execute method gets the whole AMQP message object and not just the body. See the CHANGELOG file for more details.

## Usage ##

Add the `wanup_sml_rabbit_mq` section in your configuration file:

```yaml
wanup_sml_rabbit_mq:
    connections:
        default:
            host:     'localhost'
            port:     5672
            user:     'guest'
            password: 'guest'
            vhost:    '/'
            lazy:     false
            connection_timeout: 3
            read_write_timeout: 3

            # requires php-amqplib v2.4.1+ and PHP5.4+
            keepalive: false

            # requires php-amqplib v2.4.1+
            heartbeat: 0
    producers:
        upload_picture:
            connection:       default
            exchange_options: {name: 'upload-picture', type: direct}
    consumers:
        upload_picture:
            connection:       default
            exchange_options: {name: 'upload-picture', type: direct}
            queue_options:    {name: 'upload-picture'}
            callback:         upload_picture_service
```

Here we configure the connection service and the message endpoints that our application will have. In this example your service container will contain the service `wanup_sml_rabbit_mq.upload_picture_producer` and `wanup_sml_rabbit_mq.upload_picture_consumer`. The later expects that there's a service called `upload_picture_service`.

If you don't specify a connection for the client, the client will look for a connection with the same alias. So for our `upload_picture` the service container will look for an `upload_picture` connection.

If you need to add optional queue arguments, then your queue options can be something like this:

```yaml
queue_options: {name: 'upload-picture', arguments: {'x-ha-policy': ['S', 'all']}}
```

another example with message TTL of 20 seconds:

```yaml
queue_options: {name: 'upload-picture', arguments: {'x-message-ttl': ['I', 20000]}}
```

The argument value must be a list of datatype and value. Valid datatypes are:

* `S` - String
* `I` - Integer
* `D` - Decimal
* `T` - Timestamps
* `F` - Table
* `A` - Array

Adapt the `arguments` according to your needs.

If you want to bind queue with specific routing keys you can declare it in producer or consumer config:

```yaml
queue_options:
    name: "upload-picture"
    routing_keys:
      - 'android.#.upload'
      - 'iphone.upload'
```

### Important notice - Lazy Connections ###

In a Symfony environment all services are fully bootstrapped for each request, from version >= 2.3 you can declare
a service as lazy ([Lazy Services](http://symfony.com/doc/master/components/dependency_injection/lazy_services.html)).
This bundle still doesn't support new Lazy Services feature but you can set `lazy: true` in your connection
configuration to avoid unnecessary connections to your message broker in every request.
It's extremely recommended to use lazy connections because performance reasons, nevertheless lazy option is disabled
by default to avoid possible breaks in applications already using this bundle.

### Import notice - Heartbeats ###

It's a good idea to set the ```read_write_timeout``` to 2x the heartbeat so your socket will be open. If you don't do this, or use a different multiplier, there's a risk the __consumer__ socket will timeout.

## Producers, Consumers, What? ##

In a messaging application, the process sending messages to the broker is called __producer__ while the process receiving those messages is called __consumer__. In your application you will have several of them that you can list under their respective entries in the configuration.

### Producer ###

A producer will be used to send messages to the server. In the AMQP Model, messages are sent to an __exchange__, this means that in the configuration for a producer you will have to specify the connection options along with the exchange options, which usually will be the name of the exchange and the type of it.

Now let's say that you want to process picture uploads in the background. After you move the picture to its final location, you will publish a message to server with the following information:

```php
public function indexAction($name)
{
    $msg = array('user_id' => 1235, 'image_path' => '/path/to/new/pic.png');
    $this->get('wanup_sml_rabbit_mq.upload_picture_producer')->publish(serialize($msg));
}
```

As you can see, if in your configuration you have a producer called __upload\_picture__, then in the service container you will have a service called __wanup_sml_rabbit_mq.upload\_picture\_producer__.

Besides the message itself, the `WanupSml\RabbitMqBundle\RabbitMq\Producer#publish()` method also accepts an optional routing key parameter and an optional array of additional properties. The array of additional properties allows you to alter the properties with which an `PhpAmqpLib\Message\AMQPMessage` object gets constructed by default. This way, for example, you can change the application headers.

You can use __setContentType__ and __setDeliveryMode__ methods in order to set the message content type and the message
delivery mode respectively. Default values are __text/plain__ for content type and __2__ for delivery mode.

```php
$this->get('wanup_sml_rabbit_mq.upload_picture_producer')->setContentType('application/json');
```

If you need to use a custom class for a producer (which should inherit from `WanupSml\RabbitMqBundle\RabbitMq\Producer`), you can use the `class` option:

```yaml
    ...
    producers:
        upload_picture:
            class: My\Custom\Producer
            connection: default
            exchange_options: {name: 'upload-picture', type: direct}
    ...
```

The next piece of the puzzle is to have a consumer that will take the message out of the queue and process it accordingly.

### Consumers ###

A consumer will connect to the server and start a __loop__  waiting for incoming messages to process. Depending on the specified __callback__ for such consumer will be the behavior it will have. Let's review the consumer configuration from above:

```yaml
consumers:
    upload_picture:
        connection:       default
        exchange_options: {name: 'upload-picture', type: direct}
        queue_options:    {name: 'upload-picture'}
        callback:         upload_picture_service
```

As we see there, the __callback__ option has a reference to an __upload\_picture\_service__. When the consumer gets a message from the server it will execute such callback. If for testing or debugging purposes you need to specify a different callback, then you can change it there.

Apart from the callback we also specify the connection to use, the same way as we do with a __producer__. The remaining options are the __exchange\_options__ and the __queue\_options__. The __exchange\_options__ should be the same ones as those used for the __producer__. In the __queue\_options__ we will provide a __queue name__. Why?

As we said, messages in AMQP are published to an __exchange__. This doesn't mean the message has reached a __queue__. For this to happen, first we need to create such __queue__ and then bind it to the __exchange__. The cool thing about this is that you can bind several __queues__ to one __exchange__, in that way one message can arrive to several destinations. The advantage of this approach is the __decoupling__ from the producer and the consumer. The producer does not care about how many consumers will process his messages. All it needs is that his message arrives to the server. In this way we can expand the actions we perform every time a picture is uploaded without the need to change code in our controller.

Now, how to run a consumer? There's a command for it that can be executed like this:

```bash
$ ./app/console rabbitmq:consumer -m 50 upload_picture
```

What does this mean? We are executing the __upload\_picture__ consumer telling it to consume only 50 messages. Every time the consumer receives a message from the server, it will execute the configured callback passing the AMQP message as an instance of the `PhpAmqpLib\Message\AMQPMessage` class. The message body can be obtained by calling `$msg->body`. By default the consumer will process messages in an __endless loop__ for some definition of _endless_.

If you want to be sure that consumer will finish executing instantly on Unix signal, you can run command with flag `-w`.

```bash
$ ./app/console rabbitmq:consumer -w upload_picture
```

Then the consumer will finish executing instantly.

For using command with this flag you need to install PHP with [PCNTL extension](http://www.php.net/manual/en/book.pcntl.php).

If you want to establish a consumer memory limit, you can do it by using flag `-l`. In the following example, this flag adds 256 MB memory limit. Consumer will be stopped five MB before reaching 256MB in order to avoid a PHP Allowed memory size error.

```bash
$ ./app/console rabbitmq:consumer -l 256
```

If you want to remove all the messages awaiting in a queue, you can execute this command to purge this queue:

```bash
$ ./app/console rabbitmq:purge --no-confirmation upload_picture
```

For deleting the consumer's queue, use this command:

```bash
$ ./app/console rabbitmq:delete --no-confirmation upload_picture
```

#### Idle timeout ####

If you need to set a timeout when there are no messages from your queue during a period of time, you can set the `idle_timeout` in seconds:

```yaml
consumers:
    upload_picture:
        connection:       default
        exchange_options: {name: 'upload-picture', type: direct}
        queue_options:    {name: 'upload-picture'}
        callback:         upload_picture_service
        idle_timeout:     60
```

#### Fair dispatching ####

> You might have noticed that the dispatching still doesn't work exactly as we want. For example in a situation with two workers, when all odd messages are heavy and even messages are light, one worker will be constantly busy and the other one will do hardly any work. Well, RabbitMQ doesn't know anything about that and will still dispatch messages evenly.

> This happens because RabbitMQ just dispatches a message when the message enters the queue. It doesn't look at the number of unacknowledged messages for a consumer. It just blindly dispatches every n-th message to the n-th consumer.

> In order to defeat that we can use the basic.qos method with the prefetch_count=1 setting. This tells RabbitMQ not to give more than one message to a worker at a time. Or, in other words, don't dispatch a new message to a worker until it has processed and acknowledged the previous one. Instead, it will dispatch it to the next worker that is not still busy.

From: http://www.rabbitmq.com/tutorials/tutorial-two-python.html

Be careful as implementing the fair dispatching introduce a latency that will hurt performance (see [this blogpost](http://www.rabbitmq.com/blog/2012/05/11/some-queuing-theory-throughput-latency-and-bandwidth/)). But implemeting it allow you to scale horizontally dynamically as the queue is increasing.
You should evaluate, as the blogpost reccommand, the right value of prefetch_size accordingly with the time taken to process each message and your network performance.

With RabbitMqBundle, you can configure that qos_options per consumer like that:

```yaml
consumers:
    upload_picture:
        connection:       default
        exchange_options: {name: 'upload-picture', type: direct}
        queue_options:    {name: 'upload-picture'}
        callback:         upload_picture_service
        qos_options:      {prefetch_size: 0, prefetch_count: 1, global: false}
```

### Callbacks ###

Here's an example callback:

```php
