🤖 Assistant (claude-3.7)
RocketMQTemplate 使用教程
RocketMQTemplate 是 Spring 为 RocketMQ 提供的模板工具类,大幅简化了 RocketMQ 的使用。本教程将介绍其基本用法和高级特性。
一、环境准备
1. Maven 依赖
<dependency>
<groupId>org.apache.rocketmq</groupId>
<artifactId>rocketmq-spring-boot-starter</artifactId>
<version>2.2.3</version>
</dependency>
2. 配置文件
rocketmq:
name-server: 127.0.0.1:9876
producer:
group: my-producer-group
send-message-timeout: 3000
retry-times-when-send-failed: 2
二、基础用法
1. 注入 RocketMQTemplate
@Service
public class MessageService {
@Autowired
private RocketMQTemplate rocketMQTemplate;
// 业务方法...
}
2. 发送消息
// 同步发送
public void sendMessage() {
// 简单消息发送
SendResult result = rocketMQTemplate.syncSend("topic-name", "Hello RocketMQ");
// 发送带标签的消息
SendResult tagResult = rocketMQTemplate.syncSend("topic-name:tag-A", "Tagged message");
// 发送对象消息(自动序列化)
OrderMessage order = new OrderMessage(1001L, "iPhone", 2);
SendResult objectResult = rocketMQTemplate.syncSend("order-topic", order);
// 设置超时时间
SendResult timeoutResult = rocketMQTemplate.syncSend("topic-name", "Message with timeout", 5000);
}
3. 异步发送
public void sendAsyncMessage() {
rocketMQTemplate.asyncSend("topic-name", "Async message", new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
log.info("消息发送成功: {}", sendResult);
}
@Override
public void onException(Throwable throwable) {
log.error("消息发送失败", throwable);
}
});
// Lambda 简化写法
rocketMQTemplate.asyncSend("topic-name", "Async with lambda",
sendResult -> log.info("Success: {}", sendResult),
throwable -> log.error("Failed", throwable)
);
}
4. 单向发送(不关心结果)
public void sendOneWay() {
// 适用于不关心发送结果的场景
rocketMQTemplate.sendOneWay("topic-name", "One-way message");
}
三、高级特性
1. 顺序消息
public void sendOrderedMessage() {
// 同一个hashKey的消息会发送到同一个队列,保证顺序
String hashKey = "orderId-10001";
// 同步发送顺序消息
SendResult result = rocketMQTemplate.syncSendOrderly(
"ordered-topic",
"Ordered message 1",
hashKey
);
// 异步发送顺序消息
rocketMQTemplate.asyncSendOrderly(
"ordered-topic",
"Ordered message 2",
hashKey,
new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
log.info("顺序消息发送成功");
}
@Override
public void onException(Throwable throwable) {
log.error("顺序消息发送失败", throwable);
}
}
);
}
2. 延时消息
public void sendDelayedMessage() {
// 延时级别: 1s, 5s, 10s, 30s, 1m, 2m, 3m, 4m, 5m, 6m, 7m, 8m, 9m, 10m, 20m, 30m, 1h, 2h
// 对应延时级别 1 到 18
Message<String> message = MessageBuilder.withPayload("Delayed message")
.build();
// 发送延时消息,这里使用延时级别3,对应10秒
rocketMQTemplate.syncSend("delay-topic", message, 3000, 3);
}
3. 事务消息
@Service
public class TransactionService {
@Autowired
private RocketMQTemplate rocketMQTemplate;
public void sendTransactionMessage() {
// 构建消息
Message<String> message = MessageBuilder.withPayload("Transaction message")
.build();
// 发送事务消息
TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction(
"transaction-topic",
message,
"transactionArg" // 事务参数,会传递给本地事务执行器
);
log.info("事务消息发送结果: {}", result);
}
}
// 事务消息执行器
@RocketMQTransactionListener
public class MyTransactionListener implements RocketMQLocalTransactionListener {
@Override
public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
try {
// 执行本地事务
log.info("执行本地事务,参数: {}", arg);
// 模拟业务操作
// ...
// 事务成功,消息可以提交
return RocketMQLocalTransactionState.COMMIT;
} catch (Exception e) {
log.error("本地事务执行失败", e);
// 事务失败,消息回滚
return RocketMQLocalTransactionState.ROLLBACK;
}
}
@Override
public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
// 事务状态回查
String transactionId = msg.getHeaders


1203

被折叠的 条评论
为什么被折叠?



