All Products
Search
Document Center

ApsaraMQ for RabbitMQ:Spring integration

Last Updated:Nov 04, 2025

ApsaraMQ for RabbitMQ provides an SDK for the Spring framework. This topic describes how to integrate the Spring SDK to send and receive messages.

Prerequisites

Demo project

Click SpringBootDemo.zip to download the demo project.

Step 1: Configure parameters

In the application.properties or application.yml file, set the configuration parameters. The following example uses the application.properties file.

# The endpoint. Obtain the endpoint on the Instance Details page in the ApsaraMQ for RabbitMQ console. 
spring.rabbitmq.host=XXXXXX.amqp.aliyuncs.com
# The port used to connect to ApsaraMQ for RabbitMQ.
spring.rabbitmq.port=5672
# The static username of the instance. View the username on the Static Accounts page in the ApsaraMQ for RabbitMQ console. 
spring.rabbitmq.username=******
# The static password of the instance. View the password on the Static Accounts page in the ApsaraMQ for RabbitMQ console. 
spring.rabbitmq.password=******
# The virtual host, which provides logical isolation. View the virtual host on the Vhosts page in the ApsaraMQ for RabbitMQ console. 
spring.rabbitmq.virtual-host=test_vhost
# The message acknowledgment (Ack) mode.
# 1. none: After a consumer receives a message, the server considers the message successfully processed, regardless of whether the consumption is successful. This is the autoAck mode in RabbitMQ.
# 2. auto: The client automatically sends an ack after a message is successfully consumed. If the message fails to be processed, the client sends a nack or throws an exception. You do not need to explicitly call Channel.basicAck().
# 3. manual: Manually send an Ack. You must explicitly call Channel.basicAck() after a message is successfully consumed.
spring.rabbitmq.listener.simple.acknowledge-mode=manual

# Set the cache mode to CONNECTION. ApsaraMQ for RabbitMQ uses a distributed architecture. In CONNECTION mode, clients can connect to multiple service nodes in the cluster in a more balanced way. This method can effectively prevent load hot spots and improve the efficiency of message sending and consumption.
spring.rabbitmq.cache.connection.mode=connection
# Adjust the value as needed.
spring.rabbitmq.cache.connection.size=50
# Adjust the value as needed.
spring.rabbitmq.cache.channel.size=1

# The maximum number of unacknowledged (Ack) messages that a consumer can process at a time (QoS). The ApsaraMQ for RabbitMQ server uses min{prefetch, 100} as the QoS value. If the consumer has low processing capabilities, decrease this value.
spring.rabbitmq.listener.simple.prefetch=100
# The minimum number of concurrent consumers for the RabbitMQ listener. Adjust the value as needed.
spring.rabbitmq.listener.simple.concurrency=10
# The maximum number of concurrent consumers for the RabbitMQ listener. When the consumption rate is high enough, the client starts max-concurrency consumers to consume messages.
spring.rabbitmq.listener.simple.max-concurrency=20

You can add the following optional configurations as needed:

Optional configurations

Property

Description

spring.rabbitmq.addresses

The server addresses that the client connects to. Separate multiple addresses with commas (,).

If you set both spring.rabbitmq.host and spring.rabbitmq.addresses, the spring.rabbitmq.addresses parameter takes precedence.

spring.rabbitmq.dynamic

Specifies whether to create an AmqpAdmin bean. The default value is true.

spring.rabbitmq.connection-timeout

The connection timeout. Unit: milliseconds. A value of 0 indicates no timeout.

spring.rabbitmq.requested-heartbeat

The heartbeat timeout. Unit: seconds. The default value is 60.

spring.rabbitmq.publisher-confirms

Specifies whether to enable the publisher confirm mechanism.

spring.rabbitmq.publisher-returns

Specifies whether to enable the publisher return mechanism.

spring.rabbitmq.ssl.enabled

Specifies whether to enable SSL certificate authentication.

spring.rabbitmq.ssl.key-store

The path to the key store that holds the SSL certificate.

spring.rabbitmq.ssl.key-store-password

The password to access the key store.

spring.rabbitmq.ssl.trust-store

A trusted address with an SSL Certificate.

spring.rabbitmq.ssl.trust-store-password

The password to access the trust store.

spring.rabbitmq.ssl.algorithm

The algorithm used by SSL, such as TLSv1.2.

spring.rabbitmq.ssl.validate-server-certificate

Specifies whether to enable server certificate validation.

spring.rabbitmq.ssl.verify-hostname

Specifies whether to enable host verification.

spring.rabbitmq.cache.channel.size

The number of channels to keep in the cache.

spring.rabbitmq.cache.channel.checkout-timeout

The timeout for obtaining a channel from the cache when the cache size is reached.

Unit: milliseconds. A value of 0 means a new channel is always created.

spring.rabbitmq.cache.connection.size

The number of cached connections. This parameter is effective only in CONNECTION mode.

spring.rabbitmq.cache.connection.mode

The connection cache mode. Valid values are:

  • CHANNEL

  • CONNECTION

The CONNECTION mode is recommended.

spring.rabbitmq.listener.type

The listener container type. Valid values are:

  • simple

  • direct

The default value is simple.

spring.rabbitmq.listener.simple.auto-startup

Specifies whether to automatically start the container when the application starts. The default value is true.

spring.rabbitmq.listener.simple.acknowledge-mode

The message acknowledgment mode. Valid values are:

  • none: After a consumer receives a message, the server considers the message successfully processed, regardless of whether the consumption is successful. This is the autoAck mode in RabbitMQ.

  • manual: Manually send an Ack. You must explicitly call Basic.ack after a message is successfully consumed.

  • auto: The client automatically sends an ack after a message is successfully consumed. If the message fails to be processed, the client sends a nack or throws an exception. You do not need to explicitly call Basic.ack.

The default value is auto.

spring.rabbitmq.listener.simple.concurrency

The minimum number of consumers.

spring.rabbitmq.listener.simple.max-concurrency

The maximum number of consumers.

spring.rabbitmq.listener.simple.prefetch

The maximum number of unacknowledged (Ack) messages that a consumer can process at a time. This is equivalent to setting the QoS value by calling the Basic.qos method. If transactions are used, this value must be greater than or equal to the transaction size.

spring.rabbitmq.listener.simple.transaction-size

The number of messages to process in a transaction.

spring.rabbitmq.listener.simple.default-requeue-rejected

Specifies whether rejected messages are re-queued. The default value is true.

spring.rabbitmq.listener.simple.missing-queues-fatal

Specifies whether the listener fails if a declared queue is not available on the broker, or whether the container stops if one or more queues are deleted at runtime. The default value is true.

spring.rabbitmq.listener.simple.idle-event-interval

The interval for publishing idle container events. Unit: milliseconds.

spring.rabbitmq.template.mandatory

Specifies whether to enable mandatory messaging. The default value is false.

spring.rabbitmq.template.receive-timeout

The timeout for the receive() operation.

spring.rabbitmq.template.reply-timeout

The timeout for the sendAndReceive() operation.

Step 2: Use the SDK to send and receive messages

Produce messages

In RabbitMQService, obtain RabbitTemplate through dependency injection and call its send method to send a message.

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Service
public class RabbitMQService {
    
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMessage(String exchange, String routingKey, String content) {
        // Set the MessageId.
        String msgId = UUID.randomUUID().toString();
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setMessageId(msgId);
        // Create a Message.
        Message message = new Message(content.getBytes(StandardCharsets.UTF_8), messageProperties);
        /*
         * Call the send() interface to send the message.
         * exchange: the name of the exchange.
         * routingKey: the routing key.
         * message: the message content.
         * correlationData is used for publisher confirms.
         */
        rabbitTemplate.send(exchange, routingKey, message, null);
    }
}

Consume messages

Use the @RabbitListener annotation to consume messages:

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class MessageListener {

     /**
     * Receive a message.
     * @param message The message.
     * @param channel The channel.
     * @throws IOException
     * Replace queues with the name of the queue that you created.
     */
    @RabbitListener(queues = "myQueue")
    public void receiveFromMyQueue(Message message, Channel channel) throws IOException {
        // Enter the business logic for message consumption.
        ...
        // You must return an Ack within the Ack validity period (consumption timeout). Otherwise, the confirmation is invalid and the message is redelivered.
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}

The following are common optional configurations for RabbitListener:

Optional configurations

Property

Description

ackMode

A custom message acknowledgment mode. This overwrites the spring.rabbitmq.listener.simple.acknowledge-mode setting.

admin

A reference to AmqpAdmin for AMQP resource management.

autoStartup

Specifies whether to automatically start the container when the application starts. This overwrites the spring.rabbitmq.listener.simple.auto-startup setting.

bindings

An array of bindings between queues and exchanges, which contains binding information.

concurrency

Sets the number of concurrent threads for the listener container.

errorHandler

Configures an error handler for exceptions thrown by the listener method.

exclusive

Enables the exclusive mode for a queue. This means a consumer has exclusive access to the queue, and no other consumers can receive messages from it. This feature is not currently supported.

queues

Declares the queues that this listener listens to.

queuesToDeclare

Specifies the queues to explicitly declare.