| |
|
开发:
C++知识库
Java知识库
JavaScript
Python
PHP知识库
人工智能
区块链
大数据
移动开发
嵌入式
开发工具
数据结构与算法
开发测试
游戏开发
网络协议
系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程 数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁 |
-> Java知识库 -> SpringBoot集成RocketMQ实现分布式事务 -> 正文阅读 |
|
[Java知识库]SpringBoot集成RocketMQ实现分布式事务 |
基本概念 RocketMQ 事务消息(Transactional Message)是指应用本地事务和发送消息操作可以被定义到全局事务中,要么同时成功,要么同时失败。RocketMQ 的事务消息提供类似 X/Open XA 的分布事务功能,通过事务消息能达到分布式事务的最终一致? 执行流程 ? (1) 发送方向 MQ 服务端发送消息。 项目实例 pom文件内容 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>rocketmq</artifactId> <version>0.0.1-SNAPSHOT</version> <name>rocketmq</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.5.8</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> application.ymlserver: port: 8088 rocketmq: name-server: 127.0.0.1:9876 access-channel: LOCAL producer: group: deer_message_push send-message-timeout: 3000 compress-message-body-threshold: 4096 max-message-size: 2048000 retry-times-when-send-failed: 2 retry-next-server: true 消息生产者工具类 package com.example; import cn.hutool.core.util.IdUtil; import org.apache.rocketmq.client.producer.SendCallback; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.client.producer.SendStatus; import org.apache.rocketmq.client.producer.TransactionSendResult; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Component; import java.io.Serializable; /** * @Author 何志鹏 * @Date 2022/8/30 11:44 * @Version 1.0 */ @Component public class RocketmqProducer { private final Logger logger = LoggerFactory.getLogger(RocketmqProducer.class); @Autowired private RocketMQTemplate rocketMQTemplate; /** * MQ半消息 * * @param topic target topic * @param tag topic's tag * @param msg message * @return send status */ public <T extends Serializable> SendStatus txSend(T msg, String topic, String tag) { String destination = String.format("%s:%s", topic, tag); Message<T> message = MessageBuilder.withPayload(msg) .setHeader("KEYS", IdUtil.simpleUUID()) .setHeader("DESTINATION", destination) .build(); TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction(destination, message, msg); //发送状态 String sendStatus = result.getSendStatus().name(); // 本地事务执行状态 String localTxState = result.getLocalTransactionState().name(); logger.info("send tx message sendStatus:{},localTXState:{}",sendStatus,localTxState); return result.getSendStatus(); } /** * 同步消息 * * @param msg * @param topic * @param tag * @param <T> * @return */ public <T extends Serializable> SendStatus syncSend(T msg, String topic, String tag) { String destination = String.format("%s:%s", topic, tag); Message<T> message = MessageBuilder.withPayload(msg) .setHeader("KEYS", IdUtil.simpleUUID()) .setHeader("DESTINATION", destination) .build(); return rocketMQTemplate.syncSend(destination, message).getSendStatus(); } /** * 异步消息 * * @param msg * @param topic * @param tag * @param <T> * @return */ public <T extends Serializable> void asyncSend(T msg, String topic, String tag) { String destination = String.format("%s:%s", topic, tag); Message<T> message = MessageBuilder.withPayload(msg) .setHeader("KEYS", IdUtil.simpleUUID()) .setHeader("DESTINATION", destination) .build(); rocketMQTemplate.asyncSend(destination, message, new SendCallback() { @Override public void onSuccess(SendResult sendResult) { System.out.println("============================发送成功================================="); } @Override public void onException(Throwable e) { System.out.println("============================发送失败================================="+e.getMessage()); } }); } } 创建user实体类 package com.example; import java.io.Serializable; /** * @Author 何志鹏 * @Date 2022/8/30 17:05 * @Version 1.0 */ public class User implements Serializable{ private static final long serialVersionUID = 4247558661107952933L; private Integer id; private String name; private int age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } 生产者测试类 package com.example; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class RocketmqApplicationTests { @Autowired private RocketmqProducer rocketmqProducer; @Test void contextLoads() { User user = new User(); user.setId(1); user.setName("何志鹏555555555555555555555"); user.setAge(18); rocketmqProducer.txSend(user, "topic1", "11111"); System.out.println("==========================开始发送消息========================================="); } } 消费者 package com.example; import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.springframework.stereotype.Component; /** * @Author 何志鹏 * @Date 2022/8/30 14:16 * @Version 1.0 */ @Component @RocketMQMessageListener(consumerGroup = "deer_message_push", topic = "topic1") public class RocketMQConsumer implements RocketMQListener { @Override public void onMessage(Object message) { System.out.println("收到的消息为 ================================================: " + message); } } 自定义一个RocketmqTransactionListener注解? 这边为了方便定义哪些消息需要实现事务? 如下: package com.example; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface RocketmqTransactionListener { String topic(); String selectorExpression(); } 事务监听实现 package com.example; import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.messaging.Message; import org.springframework.stereotype.Component; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; import java.util.stream.Stream; @Component @RocketMQTransactionListener(corePoolSize = 2, maximumPoolSize = 10) public class RocketmqTransactionListenerAdapter implements RocketMQLocalTransactionListener, InitializingBean { private final Logger logger = LoggerFactory.getLogger(RocketmqTransactionListenerAdapter.class); private final ApplicationContext applicationContext; private final ConcurrentHashMap<String, RocketMQLocalTransactionListener> listeners; public RocketmqTransactionListenerAdapter(ApplicationContext applicationContext) { this.applicationContext = applicationContext; this.listeners = new ConcurrentHashMap<>(); } @Override public void afterPropertiesSet() { applicationContext.getBeansWithAnnotation(RocketmqTransactionListener.class) .values() .stream() .filter(m -> RocketMQLocalTransactionListener.class.isAssignableFrom(m.getClass())) .collect(Collectors.toList()) .forEach(listener -> { RocketmqTransactionListener annotation = listener.getClass().getAnnotation(RocketmqTransactionListener.class); Stream.of(annotation.selectorExpression() .split("\\|\\|")) .forEach(tag -> { String destination = String.format("%s:%s", annotation.topic(), tag); listeners.put(destination, (RocketMQLocalTransactionListener) listener); }); }); } @Override public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { String destination = getDestination(msg); if (!listeners.containsKey(destination)) { logger.info("----------------------------------------------------"); logger.warn("{} transaction message is not supported", destination); return RocketMQLocalTransactionState.ROLLBACK; } else { RocketMQLocalTransactionListener listener = listeners.get(destination); return listener.executeLocalTransaction(msg, arg); } } @Override public RocketMQLocalTransactionState checkLocalTransaction(Message msg) { String destination = getDestination(msg); if (!listeners.containsKey(destination)) { logger.info("----------------------------------------------------"); logger.warn("{} transaction message is not supported", destination); return RocketMQLocalTransactionState.ROLLBACK; } else { RocketMQLocalTransactionListener listener = listeners.get(destination); return listener.checkLocalTransaction(msg); } } private String getDestination(Message msg) { String topic = msg.getHeaders().get("rocketmq_TOPIC", String.class); String tags = msg.getHeaders().get("rocketmq_TAGS", String.class); return String.format("%s:%s", topic, tags); } } 说明: 自定义生产者事务监听类 package com.example; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; import org.springframework.messaging.Message; import org.springframework.stereotype.Service; /** * @Author 何志鹏 * @Date 2022/8/30 16:56 * @Version 1.0 */ @Service @RocketmqTransactionListener(topic = "topic1", selectorExpression = "11111") public class ProducerListener implements RocketMQLocalTransactionListener { @Override public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { try { //todo 数据库相关逻辑 报错事务回滚 否则事务提交 int count = 1; System.err.println("==================================开始执行事务==============================="); return count > 0 ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK; } catch (Exception e) { System.err.println("=====================================事务执行失败============================================"); return RocketMQLocalTransactionState.ROLLBACK; } } @Override public RocketMQLocalTransactionState checkLocalTransaction(Message msg) { try { //todo 数据库相关逻辑 报错事务回滚 否则事务提交 boolean flag = true; return flag ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK; } catch (Exception e) { System.err.println("=====================================事务执行失败222222============================================"); return RocketMQLocalTransactionState.ROLLBACK; } } } 启动测试类RocketmqApplicationTests测试 当执行程序没有异常的情况下 ?可以看出,执行成功后,消息执行成功返回的结果为SEND_OK,本地事务执行的状态为COMMIT_MESSAGE 回滚测试 仿造异常情况下的程序? 如改动以下程序即可 重启项目进行测试? 打印日志如下: ?从执行的结果可以看出,消息执行成功返回的结果为SEND_OK,本地事务执行的状态为:ROLLBACK_MESSAGE,直接丢弃消息,所以消费端无法消费此消息? 本地事务的状态分别为提交状态、回滚状态、未知状态? 当生产者回调操作执行的结果为本地事务状态。其会发送给TC,而TC会在发送给TM,TM会根据TC发送过来的本地事务状态来决定全局事务确认指令 状态如下: TransactionStatus.CommitTransaction: 提交事务,它允许消费者消费此消息。 最后附上项目源码 ? ? ? |
|
|
上一篇文章 下一篇文章 查看所有文章 |
|
开发:
C++知识库
Java知识库
JavaScript
Python
PHP知识库
人工智能
区块链
大数据
移动开发
嵌入式
开发工具
数据结构与算法
开发测试
游戏开发
网络协议
系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程 数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁 |
360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 | -2024/11/23 13:19:47- |
|
网站联系: qq:121756557 email:121756557@qq.com IT数码 |