ActiveMQ three ways to send messages (synchronous, asynchronous, one-way)

There are three ways for MQ to send ordinary messages: reliable synchronous sending, reliable asynchronous sending, and one-way sending. This article introduces the principles, usage scenarios, and similarities and differences of each implementation, and provides code examples for reference.

Principle of reliable synchronous sending

: synchronous sending refers to the communication method in which the sender of the message sends the data and sends the next data packet after receiving the response from the receiver.

Application scenarios: This method has a wide range of application scenarios, such as important notification emails, registration SMS notifications, and marketing SMS systems.

Reliable asynchronous transmission

principle: Asynchronous transmission refers to the communication method in which the sender sends data, does not wait for the receiver to send back a response, and then sends the next data packet. The asynchronous sending of MQ requires the user to implement the asynchronous sending callback interface (SendCallback). When executing the asynchronous sending of the message, the application can return directly without waiting for the server response, receive the server response through the callback interface, and process the server response result. .

1. Configure in the connection URI
You can use the parameters supported by the connection URI to configure the mode of asynchronous sending, as follows:
cf = new ActiveMQConnectionFactory("tcp://locahost:61616?jms.useAsyncSend=true");


2. Configure at the ConnectionFactory layer
You can use the ActiveMQConnectionFactory object instance and use the asynchronous mode by setting the following:
((ActiveMQConnectionFactory)connectionFactory).setUseAsyncSend(true);


3. The configuration configured
in the Connection layer will overwrite the configuration in the ConnectionFactory layer.
You can use the ActiveMQConnection object instance and use the asynchronous mode with the following settings:
((ActiveMQConnection)connection).setUseAsyncSend(true);


Application scenario: Asynchronous sending is generally used in business scenarios where the link takes a long time and is sensitive to RT response time, such as a notification to start the transcoding service after the user's video is uploaded, and a notification to push the transcoding result after the transcoding is completed.

One-way (Oneway) sending

principle: One-way (Oneway) sending is only responsible for sending messages, does not wait for the server to respond and no callback function is triggered, that is, only sends the request and does not wait for the response. The process of sending messages in this way takes a very short time, usually at the microsecond level.



Synchronous send (send)
public class ProducerTest {
    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.ProducerId, "XXX");//Producer ID you created in the console
        properties.put(PropertyKeyConst.AccessKey,"XXX");// AccessKey Alibaba Cloud authentication, created in the Alibaba Cloud server management console
        properties.put(PropertyKeyConst.SecretKey, "XXX");// SecretKey Alibaba Cloud authentication, created in the Alibaba Cloud server management console
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");//Set the send timeout in milliseconds
        //PropertyKeyConst.ONSAddr address please input the following categories according to the actual situation:
        //Public cloud production environment: http://onsaddr-internal.aliyun.com:8080/rocketmq/nsaddr4client-internal
        //Public cloud beta environment: http://onsaddr-internet.aliyun.com/rocketmq/nsaddr4client-internet
        //Hangzhou Financial Cloud Environment: http://jbponsaddr-internal.aliyun.com:8080/rocketmq/nsaddr4client-internal
        //Hangzhou Shenzhen Cloud Environment: http://mq4finance-sz.addr.aliyun.com:8080/rocketmq/nsaddr4client-internal
        //Asia-Pacific Southeast 1 public cloud environment (only for Singapore ECS): http://ap-southeastaddr-internal.aliyun.com:8080/rocketmq/nsaddr4client-internal
        properties.put(PropertyKeyConst.ONSAddr,
          "http://onsaddr-internal.aliyun.com:8080/rocketmq/nsaddr4client-internal");//The public cloud production environment is used as an example here
        Producer producer = ONSFactory.createProducer(properties);
        // Before sending a message, the start method must be called to start the Producer, just call it once
        producer.start();
        // loop to send messages
        for (int i = 0; i < 100; i++){
            Message msg = new Message( //
                // Topic to which the message belongs
                "TopicTestMQ",
                // Message Tag can be understood as a tag in Gmail, which reclassifies the message to facilitate the Consumer to specify filter conditions to filter on the MQ server
                "TagA",
                // Message Body can be any binary data, MQ does not do anything,
                // The serialization and deserialization methods need to be negotiated between the Producer and the Consumer
                "Hello MQ".getBytes());
            // Set the business key attribute representing the message, please make it globally unique as much as possible.
            // In case you cannot receive the message normally, you can query the message through the Alibaba Cloud server management console and reissue it
            // Note: If you don't set it, it will not affect the normal sending and receiving of messages
            msg.setKey("ORDERID_" + i);
            // Send messages synchronously, as long as no exception is thrown, it is successful
            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
        // Before the application exits, destroy the Producer object
        // Note: if it is not destroyed, there is no problem
        producer.shutdown();
    }
}


Asynchronous send (sendAsync)
public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.AccessKey, "DEMO_AK");// AccessKey Alibaba Cloud authentication, created in the Alibaba Cloud server management console
        properties.put(PropertyKeyConst.SecretKey, "DEMO_SK");// SecretKey Alibaba Cloud authentication, created in the Alibaba Cloud server management console
        properties.put(PropertyKeyConst.ProducerId, "DEMO_PID");//Producer ID you created in the console
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");//Set the send timeout in milliseconds
        Producer producer = ONSFactory.createProducer(properties);
        // Before sending a message, the start method must be called to start the Producer, which only needs to be called once.
        producer.start();
        Message msg = new Message(
                // Topic to which the message belongs
                "TopicTestMQ",
                // Message Tag, which can be understood as a tag in Gmail, reclassifies the message, and is convenient for the Consumer to specify filter conditions to filter on the MQ server
                "TagA",
                // Message Body, any binary form of data, MQ does not do any intervention, requires the Producer and Consumer to negotiate a consistent serialization and deserialization method
                "Hello MQ".getBytes());
        // Set the business key attribute representing the message, please make it globally unique as much as possible. In order to facilitate you to query the message through the MQ console and re-send it if you cannot receive the message normally.
        // Note: If you don't set it, it will not affect the normal sending and receiving of messages
        msg.setKey("ORDERID_100");
        // Send a message asynchronously, and send the result back to the client through a callback.
        producer.sendAsync(msg, new SendCallback() {
            @Override
            public void onSuccess(final SendResult sendResult) {
                // Consumption sent successfully
                System.out.println("send message success. topic=" + sendResult.getTopic() + ", msgId=" + sendResult.getMessageId());
            }
            @Override
            public void onException(OnExceptionContext context) {
                // message sending failed
                System.out.println("send message failed. topic=" + context.getTopic() + ", msgId=" + context.getMessageId());
            }
        });
        // The msgId can be obtained before the callback returns.
        System.out.println("send message async. topic=" + msg.getTopic() + ", msgId=" + msg.getMsgID());
        // Before the application exits, destroy the Producer object. Note: No problem if it is not destroyed
        producer.shutdown();
    }


One-way (Oneway) send (sendOneway)
  public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.AccessKey, "DEMO_AK");// AccessKey Alibaba Cloud authentication, created in the Alibaba Cloud server management console
        properties.put(PropertyKeyConst.SecretKey, "DEMO_SK");// SecretKey Alibaba Cloud authentication, created in the Alibaba Cloud server management console
        properties.put(PropertyKeyConst.ProducerId, "DEMO_PID");//Producer ID you created in the console
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");//Set the send timeout in milliseconds
        Producer producer = ONSFactory.createProducer(properties);
        // Before sending a message, the start method must be called to start the Producer, which only needs to be called once.
        producer.start();
        // loop to send messages
        for (int i = 0; i < 100; i++){
            Message msg = new Message(
                    // Topic to which the message belongs
                    "TopicTestMQ",
                    // Message Tag,
                    // It can be understood as a label in Gmail, which reclassifies the message, which is convenient for the Consumer to specify filter conditions to filter on the MQ server
                    "TagA",
                    // Message Body
                    // Any data in binary form, MQ does not intervene, and requires the Producer and Consumer to negotiate a consistent serialization and deserialization method
                    "Hello MQ".getBytes());
            // Set the business key attribute representing the message, please make it globally unique as much as possible.
            // In case you cannot receive the message normally, you can query the message and reissue it through the Alibaba Cloud server management console.
            // Note: If you don't set it, it will not affect the normal sending and receiving of messages
            msg.setKey("ORDERID_" + i);
            // oneway sends a message, as long as no exception is thrown, it is successful
            producer.sendOneway(msg);
        }
        // Before the application exits, destroy the Producer object
        // Note: if it is not destroyed, there is no problem
        producer.shutdown();
    }



Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326567183&siteId=291194637