Step 32: Using RabbitMQ as a Message Broker

Using RabbitMQ as a Message Broker

RabbitMQ is a very popular message broker that you can use as an alternative to PostgreSQL.

Switching from PostgreSQL to RabbitMQ

To use RabbitMQ instead of PostgreSQL as a message broker:

patch_file

  1. --- a/config/packages/messenger.yaml
  2. +++ b/config/packages/messenger.yaml
  3. @@ -6,7 +6,7 @@ framework:
  4. transports:
  5. # https://symfony.com/doc/current/messenger.html#transport-configuration
  6. async:
  7. - dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
  8. + dsn: '%env(RABBITMQ_URL)%'
  9. options:
  10. use_notify: true
  11. check_delayed_interval: 60000

Adding RabbitMQ to the Docker Stack

As you might have guessed, we also need to add RabbitMQ to the Docker Compose stack:

patch_file

  1. --- a/docker-compose.yaml
  2. +++ b/docker-compose.yaml
  3. @@ -21,3 +21,7 @@ services:
  4. redis:
  5. image: redis:5-alpine
  6. ports: [6379]
  7. +
  8. + rabbitmq:
  9. + image: rabbitmq:3.7-management
  10. + ports: [5672, 15672]

Restarting Docker Services

To force Docker Compose to take the RabbitMQ container into account, stop the containers and restart them:

  1. $ docker-compose stop
  2. $ docker-compose up -d
  1. $ sleep 10

Exploring the RabbitMQ Web Management Interface

If you want to see queues and messages flowing through RabbitMQ, open its web management interface:

  1. $ symfony open:local:rabbitmq

Or from the web debug toolbar:

Step 32: Using RabbitMQ as a Message Broker - 图1

Use guest/guest to login to the RabbitMQ management UI:

Step 32: Using RabbitMQ as a Message Broker - 图2

Deploying RabbitMQ

Adding RabbitMQ to the production servers can be done by adding it to the list of services:

patch_file

  1. --- a/.symfony/services.yaml
  2. +++ b/.symfony/services.yaml
  3. @@ -18,3 +18,8 @@ files:
  4. rediscache:
  5. type: redis:5.0
  6. +
  7. +queue:
  8. + type: rabbitmq:3.7
  9. + disk: 1024
  10. + size: S

Reference it in the web container configuration as well and enable the amqp PHP extension:

patch_file

  1. --- a/.symfony.cloud.yaml
  2. +++ b/.symfony.cloud.yaml
  3. @@ -4,6 +4,7 @@ type: php:7.4
  4. runtime:
  5. extensions:
  6. + - amqp
  7. - redis
  8. - blackfire
  9. - xsl
  10. @@ -28,6 +29,7 @@ disk: 512
  11. relationships:
  12. database: "db:postgresql"
  13. redis: "rediscache:redis"
  14. + rabbitmq: "queue:rabbitmq"
  15. web:
  16. locations:

When the RabbitMQ service is installed on a project, you can access its web management interface by opening the tunnel first:

  1. $ symfony tunnel:open
  2. $ symfony open:remote:rabbitmq
  3. # when done
  4. $ symfony tunnel:close

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.