9.2.1 Adding RabbitMQ to Spring
Before you can start sending and receiving RabbitMQ messages with Spring, you’ll need to add Spring Boot’s AMQP starter dependency to your build in place of the Artemis or ActiveMQ starter you added in the previous section, as shown here:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>Adding the AMQP starter to your build will trigger autoconfiguration that will create an AMQP connection factory and RabbitTemplate beans, as well as other supporting components. Simply adding this dependency is all you need to do to start sending and receiving messages from a RabbitMQ broker with Spring. But there are a handful of useful properties you’ll want to know about, listed in table 9.4.
For development purposes, you’ll probably have a RabbitMQ broker that doesn’t require authentication running on your local machine, listening on port 5672. These properties likely won’t get much use while you’re still in development, but they’ll no doubt prove useful when your applications move into production.
Table 9.4 Properties for configuring the location and credentials of a RabbitMQ broker
| Property | Description |
|---|---|
| spring.rabbitmq.addresses | A comma-separated list of RabbitMQ broker addresses |
| spring.rabbitmq.host | The broker’s host (defaults to localhost) |
| spring.rabbitmq.port | The broker’s port (defaults to 5672) |
| spring.rabbitmq.username | The username for accessing the broker (optional) |
| spring.rabbitmq.password | The password for accessing the broker (optional) |
RUNNING A RABBITMQ BROKER
If you don’t already have a RabbitMQ broker to work with, you have several options for running RabbitMQ on your local machine. See the official RabbitMQ documentation at https://www.rabbitmq.com/download.html for the latest instructions for running RabbitMQ.
For example, suppose that as you move into production, your RabbitMQ broker is on a server named rabbit.tacocloud.com, listening on port 5673, and requiring credentials. In that case, the following configuration in your application.yml file will set those properties when the prod profile is active:
spring:
profiles: prod
rabbitmq:
host: rabbit.tacocloud.com
port: 5673
username: tacoweb
password: l3tm31nNow that RabbitMQ is configured in your application, it’s time to start sending messages with RabbitTemplate.
