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
--- a/config/packages/messenger.yaml
+++ b/config/packages/messenger.yaml
@@ -6,7 +6,7 @@ framework:
transports:
# https://symfony.com/doc/current/messenger.html#transport-configuration
async:
- dsn: '%env(MESSENGER_TRANSPORT_DSN)%'
+ dsn: '%env(RABBITMQ_URL)%'
options:
use_notify: true
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
--- a/docker-compose.yaml
+++ b/docker-compose.yaml
@@ -21,3 +21,7 @@ services:
redis:
image: redis:5-alpine
ports: [6379]
+
+ rabbitmq:
+ image: rabbitmq:3.7-management
+ ports: [5672, 15672]
Restarting Docker Services
To force Docker Compose to take the RabbitMQ container into account, stop the containers and restart them:
$ docker-compose stop
$ docker-compose up -d
$ sleep 10
Exploring the RabbitMQ Web Management Interface
If you want to see queues and messages flowing through RabbitMQ, open its web management interface:
$ symfony open:local:rabbitmq
Or from the web debug toolbar:
Use guest
/guest
to login to the RabbitMQ management UI:
Deploying RabbitMQ
Adding RabbitMQ to the production servers can be done by adding it to the list of services:
patch_file
--- a/.symfony/services.yaml
+++ b/.symfony/services.yaml
@@ -18,3 +18,8 @@ files:
rediscache:
type: redis:5.0
+
+queue:
+ type: rabbitmq:3.7
+ disk: 1024
+ size: S
Reference it in the web container configuration as well and enable the amqp
PHP extension:
patch_file
--- a/.symfony.cloud.yaml
+++ b/.symfony.cloud.yaml
@@ -4,6 +4,7 @@ type: php:7.4
runtime:
extensions:
+ - amqp
- redis
- blackfire
- xsl
@@ -28,6 +29,7 @@ disk: 512
relationships:
database: "db:postgresql"
redis: "rediscache:redis"
+ rabbitmq: "queue:rabbitmq"
web:
locations:
When the RabbitMQ service is installed on a project, you can access its web management interface by opening the tunnel first:
$ symfony tunnel:open
$ symfony open:remote:rabbitmq
# when done
$ symfony tunnel:close
Going Further
This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.