Backend Development 9 min read

Master RocketMQ Basic Messages: Lifecycle, Code Samples & Use Cases

This guide explains Apache RocketMQ’s ordinary message concept, its full lifecycle, how to create topics, Java code for sending and receiving messages, key configuration tips, and real‑world scenarios such as asynchronous decoupling and traffic‑shaping for micro‑service architectures.

Architecture & Thinking
Architecture & Thinking
Architecture & Thinking
Master RocketMQ Basic Messages: Lifecycle, Code Samples & Use Cases

1 Introduction

Earlier we learned the basics of RocketMQ and its powerful capabilities as a message middleware. RocketMQ message sending has several distinct features: ordinary messages, ordered messages, scheduled/delayed messages, and transactional messages. This article introduces the execution principle, usage, and scenarios of basic (ordinary) messages.

2 Implementation Principle

2.1 What is an ordinary message

Definition: An ordinary message is the basic message function of Apache RocketMQ, supporting simple message sending, decoupling producers and consumers, and turning synchronous operations into asynchronous processing.

2.2 Full lifecycle of an ordinary message

Initialization: the message has been prepared by the producer and is waiting to be sent.

Pending consumption: the consumer has received the message and it is awaiting processing.

Consuming: the consumer fetches the message and executes business logic (if the consumer does not respond within a specified time, RocketMQ will retry).

Consume‑complete commit: the consumer finishes processing and submits the result; the broker marks the message as processed (both success and failure), allowing traceability for a period.

Message deletion: the system periodically cleans up the oldest message data.

3 Usage Examples

3.1 Creating a Topic

In RocketMQ 5.0, the recommended way to create a topic is using the mqadmin tool and specifying the message type via an attribute parameter.

<code>sh mqadmin updateTopic -n &lt;nameserver_address&gt; -t &lt;topic_name&gt; -c &lt;cluster_name&gt; -a +message.type=NORMAL</code>

3.2 Sending and Consuming Messages

Ordinary messages can set a message key (Keys) and filter tags (Tags) for filtering and searching.

3.2.1 Sending an ordinary message (Java)

<code>// Create producer and specify group
DefaultMQProducer producer = new DefaultMQProducer("producerGroup");

// Set NameServer address
producer.setNamesrvAddr("127.0.0.1:9876"); // adjust as needed

// Start producer
producer.start();

// Prepare message
String topic = "TopicTest";
String tag = "TagA";
String key = "uniqueKey123"; // message key
String body = "Hello RocketMQ with Key and Tag";
Message msg = new Message(topic, tag, key, body.getBytes());

// Send message
SendResult sendResult = producer.send(msg);
System.out.printf("SendResult: %s%n", sendResult);

// Shut down producer
producer.shutdown();</code>

3.2.2 Receiving an ordinary message (Java)

<code>// Create consumer and specify group
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consumerGroup");

// Set NameServer address
consumer.setNamesrvAddr("127.0.0.1:9876");

// Subscribe to topic and tag
consumer.subscribe("TopicTest", "TagA");

// Register message listener
consumer.registerMessageListener(new MessageListenerConcurrently() {
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
        for (MessageExt msg : msgs) {
            String key = msg.getKeys();
            String body = new String(msg.getBody());
            System.out.printf("Receive Message - Key: %s, Body: %s%n", key, body);
            // Optional: filter based on key
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
});

// Start consumer
consumer.start();
System.out.printf("Consumer Started.%n");
</code>

Important Notes

NameServer address : ensure the IP and port used in producer.setNamesrvAddr and consumer.setNamesrvAddr match the RocketMQ cluster configuration.

Topic and Tag : the same Topic and Tag must be used for sending and receiving.

Message Key : you can filter messages by key in the consumer as shown in the example.

Transactional messages : RocketMQ also supports transactional messages, which will be covered in later articles.

Exception handling : add appropriate exception handling based on possible errors.

4 Business Use Cases

Ordinary messages are commonly used for micro‑service decoupling, event‑driven architectures, and data integration, where reliable transmission is required but strict ordering or timing is not.

4.1 Scenario 1: Asynchronous Decoupling

In a user‑registration flow, after the registration succeeds, the system needs to send a confirmation email and SMS. By publishing a message to RocketMQ, the registration service can return immediately while the email/SMS service processes the tasks asynchronously, improving response time and user experience.

4.2 Scenario 2: Traffic Shaping (Peak‑Smoothing)

On a social platform, a popular post may receive a massive number of likes in a short period, creating a traffic spike. Directly writing each like to the database could overload it. Using RocketMQ to buffer likes smooths the traffic, protecting the database and maintaining system stability.

5 Summary

Recommendation: set a globally unique business identifier (e.g., order ID or user ID) as the RocketMQ message key. This provides uniqueness, efficient querying, and easier troubleshooting.

Unique value

Convenient and efficient lookup

Facilitates issue tracing

The article covered basic message sending; upcoming articles will detail ordered messages, scheduled/delayed messages, and transactional messages.

Distributed SystemsJavaMicroservicesmessage queuerocketmq
Architecture & Thinking
Written by

Architecture & Thinking

🍭 Frontline tech director and chief architect at top-tier companies 🥝 Years of deep experience in internet, e‑commerce, social, and finance sectors 🌾 Committed to publishing high‑quality articles covering core technologies of leading internet firms, application architecture, and AI breakthroughs.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.