spring boot RocketMQ 事务消息
生产者(Producer)端 事务消息发送
Message<String> message1= MessageBuilder
.withPayload("你好")
.setHeader("KEYS","11111111").build();
TransactionSendResult sendResult = rocketMQTemplate
.sendMessageInTransaction("myGroup1","topic1:tags" ,message1,"hello");
生产者(Producer)端 消息监听器
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "myGroup1")
public class MQTheTransaction implements RocketMQLocalTransactionListener {
@Override
public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
log.info("开始本地事务");
RocketMQLocalTransactionState result = RocketMQLocalTransactionState.COMMIT;
try {
String jsonString = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
String userName = (String) o;
} catch (Exception e) {
log.error(">>>> exception message={} <<<<",e.getMessage());
result = RocketMQLocalTransactionState.UNKNOWN;
}
return result;
}
@Override
public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
log.info("事务回查");
RocketMQLocalTransactionState result = RocketMQLocalTransactionState.COMMIT;
try {
String jsonString = new String((byte[]) message.getPayload(), StandardCharsets.UTF_8);
} catch (Exception e) {
log.error("回滚");
result = RocketMQLocalTransactionState.ROLLBACK;
}
return result;
}
}
消费者 (consumer)端 监听器
@Slf4j
@Component
@RocketMQMessageListener(topic = "topic1", consumerGroup = "${rocketmq.cousumer.group}", messageModel = MessageModel.BROADCASTING,selectorType= SelectorType.TAG,selectorExpression="*")
public class 事务消费者 implements RocketMQListener<MessageExt>, RocketMQPushConsumerLifecycleListener {
private int count = 0;
@Override
public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
System.out.println("开启");
defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
for (MessageExt messageExt : msgs) {
System.out.println("重试次数:" + messageExt.getReconsumeTimes());
System.out.println("key:" + messageExt.getKeys());
if (count == 0) {
count++;
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
System.out.println("接受到的消息:" + new String(messageExt.getBody()));
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
});
}
@Override
public void onMessage(MessageExt messageExt) {
}
}