Getting Started with RocketMQ: Installation, Core Concepts, and Spring Boot Integration
This guide walks through installing RocketMQ 4.5.1, launching NameServer and broker, testing with sample producer/consumer scripts, explains core components and console setup, shows Spring Boot starter integration with example code, and demonstrates sending normal, ordered, and transactional messages.
Message Queue (MQ) is a cross‑process communication mechanism used to decouple and asynchronously process time‑consuming tasks such as email or SMS notifications, and to smooth traffic spikes.
Environment setup
Download and unzip RocketMQ 4.5.1, start the NameServer and Broker, and verify the logs.
wget https://archive.apache.org/dist/rocketmq/4.5.1/rocketmq-all-4.5.1-bin-release.zip unzip rocketmq-all-4.5.1-bin-release.zip nohup sh mqnamesrv & tail -f ~/logs/rocketmqlogs/namesrv.log nohup sh mqbroker -n localhost:9876 & tail ~/logs/rocketmqlogs/broker.log vim runbroker.sh # adjust memory settings if neededFirst experience
Use the provided demo scripts to send and receive a message.
sh tools.sh org.apache.rocketmq.example.quickstart.Producer sh tools.sh org.apache.rocketmq.example.quickstart.ConsumerCore architecture
RocketMQ consists of Producers, Consumers, Brokers, and NameServers. Producers obtain broker routes from the NameServer, send messages to a Broker, which stores them in MessageQueues organized by Topic. Consumers retrieve messages similarly.
Broker – stores and dispatches messages
NameServer – route manager
Producer – sends messages
Consumer – receives messages
Topic – logical grouping of messages
Message Queue – parallel storage units within a Topic
Producer/Consumer Group – logical grouping of instances
Console
A Spring Boot based console can be downloaded, configured with the NameServer address, packaged with Maven and run.
mvn clean package -Dmaven.test.skip=true java -jar rocketmq-console-ng-1.0.0.jar brokerIP1=192.168.190.134 nameSrvAddr=192.168.190.134:9876Spring Boot integration
Add the starter dependency:
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>Example producer code:
public static void main(String[] args) throws Exception {
DefaultMQProducer producer = new DefaultMQProducer("myproducer-group");
producer.setNamesrvAddr("192.168.190.134:9876");
producer.start();
Message message = new Message("myTopic", "myTag", "myMessage".getBytes());
SendResult result = producer.send(message, 10000);
System.out.println(result);
producer.shutdown();
}Example consumer code:
public static void main(String[] args) throws Exception {
DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("myconsumer-group");
consumer.setNamesrvAddr("192.168.190.134:9876");
consumer.subscribe("myTopic", "*");
consumer.registerMessageListener((list, ctx) -> {
System.out.println("Received: " + list);
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
});
consumer.start();
}Message types
RocketMQ supports normal, ordered, and transactional messages.
Normal messages can be sent synchronously, asynchronously, or one‑way:
@Test
public void testSyncSend() {
SendResult result = rocketMQTemplate.syncSend("myTopic1", "testSyncSend", 10000);
System.out.println(result);
} @Test
public void testAsyncSend() throws InterruptedException {
rocketMQTemplate.asyncSend("myTopic2", "testAsyncSend", new SendCallback() {
@Override public void onSuccess(SendResult sendResult) { System.out.println(sendResult); }
@Override public void onException(Throwable e) { System.out.println(e); }
});
Thread.sleep(300000);
} @Test
public void testOneWay() {
rocketMQTemplate.sendOneWay("myTopic3", "testOneWay");
}Ordered messages require a hash key to route to the same queue:
rocketMQTemplate.sendOneWayOrderly("myTopic", "testOneWayOrderly", "a");Transactional messages enable distributed transaction consistency. A producer sends a transactional message, the local transaction returns COMMIT or ROLLBACK, and the broker may perform a check‑back if needed.
rocketMQTemplate.sendMessageInTransaction("tx-producer-group", "tx-topic",
MessageBuilder.withPayload(order).setHeader("txId", txId).build(), order); @Service
@RocketMQTransactionListener(txProducerGroup = "tx-producer-group")
public class OrderServiceImplListener implements RocketMQLocalTransactionListener {
@Autowired private OrderService orderService;
@Autowired private TxLogMapper txLogMapper;
@Override
public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
// local transaction logic
}
@Override
public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
// transaction check logic
}
} @Transactional
public void createOrder(Order order, String txId) {
orderMapper.insert(order);
TxLog txLog = new TxLog();
txLog.setTxId(txId);
txLog.setDate(new Date());
txLogMapper.insert(txLog);
} @Data
@TableName("shop_txlog")
public class TxLog {
@TableId(type = IdType.AUTO)
private String txId;
private Date date;
}The article provides a complete beginner‑friendly guide to installing, configuring, and using RocketMQ, including Spring Boot integration and the three main message types.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.