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 static username-password pair for your client in the console. This feature is consistent with that of open source RabbitMQ.
Notice Assume that you use an SDK to send or receive messages on a client. If a connection is established every time you send or receive messages, a large number of network and broker resources are consumed. Meanwhile, protection against SYN flood attacks on the broker may be triggered. Therefore, we recommend that you use persistent connections. For more information, see Connection.

Process to send and receive messages

mass

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

Install 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>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.6</version>
</dependency>

Produce a message

Create, compile, and run ProducerTest.java.

import com.rabbitmq.client.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;
import java.util.UUID;

public class ProducerTest {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        // Specify an endpoint. You can view the endpoint of your instance on the Instances page in the Message Queue for RabbitMQ console. 
        factory.setHost("xxx.xxx.aliyuncs.com");
        // Specify a username. You can view your username on the Static Accounts Alerting page in the Message Queue for RabbitMQ console. 
        factory.setUsername("${UserName}");
        // Specify the password of the username. You can view the password on the Static Accounts Alerting page in the Message Queue for RabbitMQ console. 
        factory.setPassword("${PassWord}");
        // Specify whether to turn on the automatic recovery switch. If you set it to true, the switch is turned on. If you set it to false, the switch is turned off. 
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(5000);
        // Specify a vhost name. Make sure that the vhost is created in the Message Queue for RabbitMQ console. 
        factory.setVirtualHost("${VhostName}");
        // Specify a default port. Use port 5672 for an unencrypted connection and port 5671 for an encrypted connection. 
        factory.setPort(5672);
        // Specify timeout periods based on the network environment. 
        factory.setConnectionTimeout(30 * 1000);
        factory.setHandshakeTimeout(30 * 1000);
        factory.setShutdownTimeout(0);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // Send a message. 
        for (int i = 0; i < 100; i++  ) {
            // Make sure that ${ExchangeName} already exists in the Message Queue for RabbitMQ console and that the exchange type is consistent with that in the console. 
            // Set BindingKey to a 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();
    }
}

Consume a message

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 an endpoint. You can view the endpoint of your instance on the Instances page in the Message Queue for RabbitMQ console. 
        factory.setHost("xxx.xxx.aliyuncs.com");
        // Specify a username. You can view your username on the Static Accounts Alerting page in the Message Queue for RabbitMQ console. 
        factory.setUsername("${Username}");
        // Specify the password of the username. You can view the password on the Static Accounts Alerting page in the Message Queue for RabbitMQ console. 
        factory.setPassword("${Password}");
        // Set the parameters to enable automatic recovery. 
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(5000);
        // Specify a vhost name. Make sure that the vhost is created in the Message Queue for RabbitMQ console. 
        factory.setVirtualHost("${VhostName}");
        // Specify a default port. Use port 5672 for an unencrypted connection and port 5671 for an encrypted connection. 
        factory.setPort(5672);
        factory.setConnectionTimeout(300 * 1000);
        factory.setHandshakeTimeout(300 * 1000);
        factory.setShutdownTimeout(0);
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        // 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();
    }
}

For more information about the consumption of messages, see Message log management.

This topic uses only SDK for Java as an example and describes how to send and receive messages. For more information about SDK for other programming languages or frameworks, see Overview.