This topic provides the sample code for sending and subscribing to delayed messages through the Java SDK over TCP.

Prerequisites

You have completed the following operations:

Background information

Delayed messages are delivered to a consumer after a delay, for example three seconds, from when they are sent to the Message Queue for Apache RocketMQ broker. Such messages are sent when a time window is required between the production and consumption of the messages, or when tasks need to be triggered after a delay. Delayed messages are similar to delayed queues.

For the concepts and use precautions of delayed messages, see Scheduled messages and delayed messages.

Note For new users, we recommend that you read the Demo Project (TCP) to learn how to build a Message Queue for Apache RocketMQ project before sending and subscribing to a message.

Send delayed messages

For more information about the sample code, see Message Queue for Apache RocketMQ code library.

The sample code for sending delayed messages is as follows:

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.SendResult;
import java.util.Properties;

public class ProducerDelayTest {
    public static void main(String[] args) {
        Properties properties = new Properties();
        // The AccessKey ID you created in the Alibaba Cloud console for identity authentication.
        properties.put(PropertyKeyConst.AccessKey, "XXX");
        // The AccessKey secret you created in the Alibaba Cloud console for identity authentication.
        properties.put(PropertyKeyConst.SecretKey, "XXX");
        // The TCP endpoint. Go to the Instances page in the Message Queue for Apache RocketMQ console, and view the endpoint in the Endpoint Information section.
        properties.put(PropertyKeyConst.NAMESRV_ADDR,
          "XXX");

        Producer producer = ONSFactory.createProducer(properties);
        // Before sending a message, call the start method once to start the producer.
        producer.start();
        Message msg = new Message( //
                // The topic you created in the console.
                "Topic",
                // The message tag, which is similar to a Gmail tag. It is used to sort messages, enabling the consumer to filter messages on the Message Queue for Apache RocketMQ broker based on the specified criteria.
                "tag",
                // The message body in any binary format. Message Queue for Apache RocketMQ does not process the message body. The producer and consumer must negotiate consistent serialization and deserialization methods.
                "Hello MQ".getBytes());
        // The message key, which must be globally unique.
        // A unique identifier enables you to query a message and resend it in the console if you fail to receive the message.
        // Note: Messages can still be sent and received even if this attribute is not set.
        msg.setKey("ORDERID_100");
        try {
            // The message delivery delay time in milliseconds (ms). Messages are delivered after the specified delay against the current time, for example, three seconds.
            long delayTime = System.currentTimeMillis() + 3000;

            // The message delivery time.
            msg.setStartDeliverTime(delayTime);

            SendResult sendResult = producer.send(msg);
            // The synchronous message transmission result, which is successful if no exception occurs.
            if (sendResult ! = null) {
            System.out.println(new Date() + " Send mq message success. Topic is:" + msg.getTopic() + " msgId is: " + sendResult.getMessageId());
            }
            } catch (Exception e) {
            // The message failed to be sent and must be resent. The system can resend the message or store message data persistently.
            System.out.println(new Date() + " Send mq message failed. Topic is:" + msg.getTopic());
            e.printStackTrace();
        }
        // Destroy the producer object before exiting the application.<br>
        // Note: You can choose not to destroy the producer object.
        producer.shutdown();
    }
}           

Subscribe to delayed messages

The mode for subscribing to delayed messages is the same as that for subscribing to normal messages. For more information, see Subscribe to messages.