This topic describes how to use SDK for Java to send and receive messages.

Prerequisites

Create resources

Background information

When you access Message Queue for RabbitMQ from a client, Message Queue for RabbitMQ authenticates your permissions based on your username and password. Message Queue for RabbitMQ allows you to create a pair of static username and password for your client in the console. This feature is consistent with that of open source RabbitMQ .
Notice If you use an SDK to send or receive messages on your client, 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 even 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 an endpoint

You must obtain an endpoint of your instance in the Message Queue for RabbitMQ console. Before you send and receive messages, you must specify the endpoint in the code of the producer and consumer. Then, the producer and consumer can access the Message Queue for RabbitMQ instance by using the endpoint.

  1. Log on to the Message Queue for RabbitMQ console.
  2. In the Resource Distribution section of the Overview page, select the region where your instance is located.
  3. On the Instances page, click the name of your instance.
  4. On the Endpoint Information tab of the Instance Details page, move the pointer to the type of the endpoint that you want to use. Then, click the copy icon on the right side of the endpoint to copy the endpoint.
    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 select 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 virtual private cloud (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 Resource Distribution section of the Overview page, select the region where your instance is located.
  3. On the Instances page, click the name of your instance.
  4. In the left-side navigation pane, click Static Accounts.
  5. On the Static Accounts page, click Create Username/Password.
  6. In the Create Username/Password panel, set AccessKey ID and AccessKey Secret. Then, click OK.
    On the Static Accounts page, the created pair of static username and password appears. The password is masked. Username and password
  7. In the Password column of the created pair of static username and password, click Display to view the password that corresponds to the username.

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 an endpoint.
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 Resource Access Management (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 obtain the static 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 obtain the static password of a static username 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 vhost Details page. For more information about how to view a vhost, see View details about a vhost.
ExchangeName ExchangeTest The exchange that you created in the Message Queue for RabbitMQ instance. In the Message Queue for RabbitMQ console, you can search for an exchange based on the instance ID and vhost 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 of your instance 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 of your instance 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.