Message Queue for Apache RocketMQ provides three modes to send normal messages, including synchronous transmission, asynchronous transmission, and one-way transmission. This topic describes the principles, scenarios, sample code, and comparison between the three transmission modes.

Synchronous transmission

  • Principle
    In synchronous transmission mode, the sender sends another message only after receiving a response from the broker.sync
  • Scenarios

    This mode is applicable to many scenarios, such as important notification emails, short messaging service (SMS) registration notifications, and SMS marketing systems.

  • Sample code
        import com.aliyun.openservices.ons.api.Message;
        import com.aliyun.openservices.ons.api.Producer;
        import com.aliyun.openservices.ons.api.SendResult;
        import com.aliyun.openservices.ons.api.ONSFactory;
        import com.aliyun.openservices.ons.api.PropertyKeyConst;
    
        import java.util.Properties;
    
        public class ProducerTest {
            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 message transmission timeout interval, in milliseconds.
                properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
                // The TCP endpoint. Go to the Instances page in the Message Queue for Apache RocketMQ console, and view the endpoint in the Endpoint Information area.
                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();
    
                // Send messages cyclically.
                for (int i = 0; i < 100; i++){
                    Message msg = new Message( //
                        // The topic of the message.
                        "TopicTestMQ",
                        // 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.
                        "TagA",
                        // The message body in any binary format. Message Queue for Apache RocketMQ does not process the message body.
                        // The producer and consumer must negotiate the 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 Alibaba Cloud 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_" + i);
    
                    try {
                        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.
                // Note: You can choose not to destroy the producer object.
                producer.shutdown();
            }
        }               

Asynchronous transmission

  • Principle

    In asynchronous transmission mode, the sender sends the second message after the first one, without waiting for the response from the broker. Message Queue for Apache RocketMQ synchronous transmission requires implementation of the SendCallback interface. The sender sends the second message immediately after the first one, without waiting for the response from the broker. The sender calls the SendCallback interface to receive responses from the broker and processes the responses.

    async
  • Scenarios

    This mode is generally used in time-consuming links for business scenarios that are sensitive to the response time. For example, after a user uploads a video, a notification is sent immediately to enable transcoding. After transcoding is completed, a notification is sent to push transcoding results.

  • Sample code
        import com.aliyun.openservices.ons.api.Message;
        import com.aliyun.openservices.ons.api.OnExceptionContext;
        import com.aliyun.openservices.ons.api.Producer;
        import com.aliyun.openservices.ons.api.SendCallback;
        import com.aliyun.openservices.ons.api.SendResult;
        import com.aliyun.openservices.ons.api.ONSFactory;
        import com.aliyun.openservices.ons.api.PropertyKeyConst;
    
        import java.util.Properties;
    
        public class ProducerTest {
            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 message transmission timeout interval, in milliseconds.
                properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
                // The TCP endpoint. Go to the Instances page in the Message Queue for Apache RocketMQ console, and view the endpoint in the Endpoint Information area.
                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 of the message.
                        "TopicTestMQ",
                        // 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.
                        "TagA",
                        // 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");
    
                // The asynchronous message sending result, which is returned to the client by the callback function.
                producer.sendAsync(msg, new SendCallback() {
                    @Override
                    public void onSuccess(final SendResult sendResult) {
                        // The message is sent to the consumer.
                        System.out.println("send message success. topic=" + sendResult.getTopic() + ", msgId=" + sendResult.getMessageId());
                    }
    
                    @Override
                    public void onException(OnExceptionContext context) {
                        // The message failed to be sent and must be resent. The system can resend the message or store message data persistently.
                        System.out.println("send message failed. topic=" + context.getTopic() + ", msgId=" + context.getMessageId());
                    }
                });
    
                // The message ID can be obtained before the callback function returns the result.
                System.out.println("send message async. topic=" + msg.getTopic() + ", msgId=" + msg.getMsgID());
    
                // Destroy the producer object before exiting the application. Note: You can choose not to destroy the producer object.
                producer.shutdown();
            }
        }                

Send messages in one-way mode

  • Principle

    The producer simply sends messages or requests without waiting for any response from the broker or triggering the callback function. In this mode, transmission can be completed within microseconds.

    oneway
  • Scenarios

    This mode is applicable to scenarios where message transmission takes a short time and has no demanding reliability requirements, such as log collection.

  • Sample code
        import com.aliyun.openservices.ons.api.Message;
        import com.aliyun.openservices.ons.api.Producer;
        import com.aliyun.openservices.ons.api.ONSFactory;
        import com.aliyun.openservices.ons.api.PropertyKeyConst;
    
        import java.util.Properties;
    
        public class ProducerTest {
            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 message transmission timeout interval, in milliseconds.
                properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
                // The TCP endpoint. Go to the Instances page in the Message Queue for Apache RocketMQ console, and view the endpoint in the Endpoint Information area.
                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();
                // Send messages cyclically.
                for (int i = 0; i < 100; i++){
                    Message msg = new Message(
                            // The topic of the message.
                            "TopicTestMQ",
                            // The message tag.
                            // It 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.
                            "TagA",
                            // The message body.
                            // It is in any binary format. Message Queue for Apache RocketMQ does not process the message body. The producer and consumer must negotiate the 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 Alibaba Cloud 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_" + i);
    
                    // In one-way transmission mode, the producer does not wait for the response from the broker. Therefore, data loss occurs if messages that fail to be delivered are not retransmitted. If data loss is not acceptable, we recommend that you use the reliable synchronous or asynchronous transmission mode.
                    producer.sendOneway(msg);
                }
    
                // Destroy the producer object before exiting the application.
                // Note: You can choose not to destroy the producer object.
                producer.shutdown();
            }
        }              

Comparison of the three transmission modes

The following table summarizes the features and major differences between the three modes.

Transmission mode TPS Response Reliability
Synchronous transmission High Yes No message loss
Asynchronous transmission High Yes No message loss
One-way transmission Highest None Possible message loss