Help Center/ Distributed Message Service for RabbitMQ/ Developer Guide/ Connecting to a RabbitMQ Instance with Spring Boot
Updated on 2025-12-22 GMT+08:00

Connecting to a RabbitMQ Instance with Spring Boot

This topic describes how to connect to a RabbitMQ instance with Spring Boot to produce and consume messages.

Before getting started, ensure that you have collected the information described in Collecting Connection Information.

The connection examples in this document are applicable for both RabbitMQ 3.x.x and AMQP-0-9-1.

Add the spring-boot-starter-amqp Dependency to pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-amqp</artifactId>
  <version>2.3.1.RELEASE</version>
</dependency>

(Optional) Writing Configuration in application.properties

If SSL is enabled for the RabbitMQ instance, write the following configuration in application.properties.

#Enable SSL
spring.rabbitmq.ssl.enabled=true
#SSL algorithm
spring.rabbitmq.ssl.algorithm=TLSv1.2
#Whether to verify the host
spring.rabbitmq.ssl.verify-hostname=false
#Whether to validate the server certificate
spring.rabbitmq.ssl.validate-server-certificate=false

Producing Messages

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProducerController {
    private static final Logger LOG = LoggerFactory.getLogger(ProducerController.class);

    @Autowired
    private RabbitTemplate;

    @GetMapping(value = "/send")
    public boolean send(String msg, Long delayTime) {
        rabbitTemplate.convertAndSend("ex-sour", "abc", msg,
            message -> {
                /**
                 * Set delay time
                 */
                message.getMessageProperties().setHeader("x-delay", delayTime);
                return message;
            });
        LOG.info("send delayed message: {}, delay: {}ms", msg, delayTime);
        return true;
    }
}

Consuming Messages

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;


@Component
public class ReceiveMsgService {
    Logger LOG =  LoggerFactory.getLogger(ReceiveMsgService.class);

    @RabbitListener(queues = "test")
    public void receive(String message) {
        SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LOG.info("receive message: {}", message + " time: " + simpleDateFormat.format(new Date()));
    }
}