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

If an open source RabbitMQ client needs to access Alibaba Cloud services, you must use the AccessKey ID and AccessKey secret of your Alibaba Cloud account or a RAM user within the account to generate a pair of username and password. In the code of open source RabbitMQ SDK, set the userName parameter to the generated username and set the passWord parameter to the generated password. Message Queue for RabbitMQ authenticates the open source RabbitMQ client by using the pair of username and password.
Notice If your client uses an SDK to send or receive messages, we recommend that you use persistent connections. This way, the client does not need to establish connections every time you use the client to send or receive messages. Frequent creation of connections consumes a large number of network and broker resources and may trigger protection against SYN flood attacks on the broker. For more information, see Connection.

Messaging process (Java used as an example)

Use open source RabbitMQ SDK to send and receive messages
Note Message Queue for RabbitMQ is compatible with open source RabbitMQ. For more information about open source RabbitMQ SDK for other programming languages, see Table 1.

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.

  1. Log on to the Message Queue for RabbitMQ console.
  2. In the top navigation bar, select the region where your instance resides.
  3. In the left-side navigation pane, click Instances.
  4. On the Instances page, select your instance. In the Basic Information section, find the endpoint of the required network type and click the endpoint to copy it.
    Type Description Example
    Public endpoint You can access an instance from the Internet to read and write data. By default, pay-as-you-go instances have public endpoints. To use a public endpoint for a subscription instance, you must configure a public endpoint when you create the subscription instance. XXX.mq-amqp.cn-hangzhou-a.aliyuncs.com
    VPC endpoint You can access an instance from a VPC to read and write data. By default, both pay-as-you-go and subscription instances have VPC endpoints. XXX.mq-amqp.cn-hangzhou-a-internal.aliyuncs.com

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

  1. Log on to the Message Queue for RabbitMQ console.
  2. In the top navigation bar, select the region where your instance resides.
  3. In the left-side navigation pane, click Static Accounts.
  4. On the Static Accounts page, click Create Username/Password.
  5. In the Create Username/Password dialog box, specify AccessKey ID, AccessKey Secret, and Instance ID, and click OK.
    The Static Accounts page displays the created static username/password pair. By default, the password is masked.pg_Username/Password Management page
  6. Click Display in the Password column.
    The password is unmasked in the Password column.show password

Produce messages

Create, compile, and run ProducerTest.java.

Notice Before you compile ProducerTest.java and run it to produce messages, you must set the parameters described in Table 1 based on the comments in the code.
Table 1. Parameters
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.

Notice Before you compile ConsumerTest.java and run it to subscribe to messages, you must set the parameters described in Table 1 based on the comments in the code.
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 
Note Message Queue for RabbitMQ is compatible with open source RabbitMQ. For more information about parameters, see RabbitMQ client documentation.

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.