This topic describes how to use open source RabbitMQ SDK to send and receive messages in the scenario where a pair of username and password is used for authentication. The username and password are generated by using the AccessKey pair of your Alibaba Cloud account or a Resource Access Management (RAM) user within the account. This topic helps you better understand the complete process of sending and receiving messages. In this topic, SDK for Java is used as an example. The process of sending and receiving messages by using open source Rabbit SDK for other programming languages or frameworks is similar to that described in this topic.
Background information
Messaging process (Java used as an example)

Obtain endpoints
You must obtain the endpoint of your instance in the Message Queue for RabbitMQ console. When you send or receive messages, you must configure the endpoint on the producer or consumer client. Otherwise, you cannot access the Message Queue for RabbitMQ instance.
Add Java dependencies
Add the following dependencies to the pom.xml file:
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.5.0</version> <!-- All versions of open source RabbitMQ are supported. -->
</dependency>
Generate a pair of username and password
Produce messages
Create, compile, and run ProducerTest.java.
Parameter | Example | Description |
---|---|---|
hostName | 1880770****.mq-amqp.cn-hangzhou-a.aliyuncs.com | The endpoint of the Message Queue for RabbitMQ instance. For more information about how to obtain an endpoint of an instance, see Obtain endpoints. |
Port | 5672 | The default port. Use port 5672 for non-encrypted connections and port 5671 for encrypted connections. |
userName | MjoxODgwNzcwODY5MD**** | The static username that is generated in the Message Queue for RabbitMQ console. Message Queue for RabbitMQ encodes the AccessKey pair of your Alibaba Cloud account or a RAM user within the account and the ID of the Message Queue for RabbitMQ instance in Base64 to obtain a static username. In the Message Queue for RabbitMQ console, you can view the created username on the Static Accounts page. |
passWord | NDAxREVDQzI2MjA0OT**** | The static password that is generated in the Message Queue for RabbitMQ console. Message Queue for RabbitMQ uses the HMAC-SHA1 algorithm to generate a signature based on the AccessKey secret of your Alibaba Cloud account or a RAM user within the account and the timestamp parameter, which indicates the current system time. Then, Message Queue for RabbitMQ encodes the signature and the timestamp parameter in Base64 to obtain a static password. In the Message Queue for RabbitMQ console, you can view the created username and password on the Static Accounts page. |
virtualHost | Test | The vhost that you created in the Message Queue for RabbitMQ instance. In the Message Queue for RabbitMQ console, you can view the vhost on the vhosts page. For more information about how to view a vhost, see View vhost details. |
ExchangeName | ExchangeTest | The exchange that you created in the Message Queue for RabbitMQ instance. In the Message Queue for RabbitMQ console, you can view the exchange on the Exchanges page. |
BindingKey | BindingKeyTest | The binding key that is used to bind the exchange with a queue in Message Queue for RabbitMQ. In the Message Queue for RabbitMQ console, you can view the bindings of the exchange and obtain the binding key on the Exchanges page. |
QueueName | QueueTest | The queue that you created in the Message Queue for RabbitMQ instance. This parameter is required only when you subscribe to messages. In the Message Queue for RabbitMQ console, you can view the bindings of the exchange and obtain the queues that are bound to the exchange on the Exchanges page. |
import com.rabbitmq.client.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;
import java.util.HashMap;
import java.util.UUID;
public class ProducerTest {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
// Specify the endpoint. You can view the endpoint on the Instance Details page in the Message Queue for RabbitMQ console.
factory.setHost("xxx.xxx.aliyuncs.com");
// Specify the username. You can view the username on the Static Accounts page in the Message Queue for RabbitMQ console.
factory.setUsername("${UserName}");
// Specify the password that corresponds to the username. You can view the password on the Static Accounts page in the Message Queue for RabbitMQ console.
factory.setPassword("${PassWord}");
// Enable automatic connection recovery. If you set the value to true, automatic connection recovery is enabled. If you set the value to false, automatic connection recovery is disabled.
factory.setAutomaticRecoveryEnabled(true);
factory.setNetworkRecoveryInterval(5000);
// Specify the vhost name. Make sure that the vhost has been created in the Message Queue for RabbitMQ console.
factory.setVirtualHost("${VhostName}");
// Specify the default port. Use port 5672 for non-encrypted connections and port 5671 for encrypted connections.
factory.setPort(5672);
// Set a timeout period based on the network environment.
factory.setConnectionTimeout(30 * 1000);
factory.setHandshakeTimeout(30 * 1000);
factory.setShutdownTimeout(0);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("${ExchangeName}", "${ExchangeType}", true, false, false, null);
channel.queueDeclare("${QueueName}", true, false, false, new HashMap<String, Object>());
channel.queueBind("${QueueName}", "${ExchangeName}", "${BindingKey}");
// Send a message.
for (int i = 0; i < 100; i++ ) {
// Set ${ExchangeName} to an exchange that already exists in the Message Queue for RabbitMQ console. Make sure that the type of the exchange is consistent with that in the console.
// Set BindingKey to the corresponding binding key based on your business requirements.
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().messageId(UUID.randomUUID().toString()).build();
channel.basicPublish("${ExchangeName}", "BindingKey", true, props,
("messageBody" + i).getBytes(StandardCharsets.UTF_8));
}
connection.close();
}
}
Subscribe to messages
Create, compile, and run ConsumerTest.java.
import com.rabbitmq.client.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;
public class ConsumerTest {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
// Specify the endpoint. You can view the endpoint on the Instance Details page in the Message Queue for RabbitMQ console.
factory.setHost("xxx.xxx.aliyuncs.com");
// Specify the username. You can view the username on the Static Accounts page in the Message Queue for RabbitMQ console.
factory.setUsername("${Username}");
// Specify the password that corresponds to the username. You can view the password on the Static Accounts page in the Message Queue for RabbitMQ console.
factory.setPassword("${Password}");
// Enable automatic connection recovery. If you set the value to true, automatic connection recovery is enabled. If you set the value to false, automatic connection recovery is disabled.
factory.setAutomaticRecoveryEnabled(true);
factory.setNetworkRecoveryInterval(5000);
// Specify the vhost name. Make sure that the vhost has been created in the Message Queue for RabbitMQ console.
factory.setVirtualHost("${VhostName}");
// Specify the default port. Use port 5672 for non-encrypted connections and port 5671 for encrypted connections.
factory.setPort(5672);
factory.setConnectionTimeout(300 * 1000);
factory.setHandshakeTimeout(300 * 1000);
factory.setShutdownTimeout(0);
Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
// Set ${ExchangeName} to an exchange that already exists in the Message Queue for RabbitMQ console. Make sure that the type of the exchange is consistent with that in the console.
AMQP.Exchange.DeclareOk exchangeDeclareOk = channel.exchangeDeclare("${ExchangeName}", "${ExchangeType}", true, false, false, null);
// Set ${QueueName} to a queue that already exists in the Message Queue for RabbitMQ console.
AMQP.Queue.DeclareOk queueDeclareOk = channel.queueDeclare("${QueueName}", true, false, false, new HashMap<String, Object>());
// Set BindingKeyTest to the binding key that is used to bind the queue to the exchange.
AMQP.Queue.BindOk bindOk = channel.queueBind("${QueueName}", "${ExchangeName}", "BindingKeyTest");
// Consume a message.
channel.basicConsume("${QueueName}", false, "ConsumerTag", new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body)
throws IOException {
// Process the received message based on the business logic.
System.out.println("Received: "+ new String(body, StandardCharsets.UTF_8) + ", deliveryTag: " + envelope.getDeliveryTag() + ", messageId: " + properties.getMessageId());
channel.basicAck(envelope.getDeliveryTag(), false);
}
});
connection.close();
}
}
Cancel
Query messages
If you want to check whether the message is sent to Message Queue for RabbitMQ, you can query the message in the Message Queue for RabbitMQ console. For more information, see Message query.