【BUG事务内消息发送】事务内消息发送,事务还未结束,消息发送已被消费,查无数据怎么解决?

问题描述

在一个事务内完成插入操作,通过MQ异步通知其他微服务进行事件处理。

由于是在事务内发送,其他服务消费消息,查询数据时还不存在如何解决呢?


解决方案

通过spring-tx包的TransactionSynchronizationManager事务管理器解决。

java 复制代码
public abstract class TransactionSynchronizationManager {

	private static final ThreadLocal<Set<TransactionSynchronization>> synchronizations =
			new NamedThreadLocal<>("Transaction synchronizations");

	/**
	 * Return if transaction synchronization is active for the current thread.
	 * Can be called before register to avoid unnecessary instance creation.
	 * @see #registerSynchronization
	 */		
	public static boolean isSynchronizationActive() {
		return (synchronizations.get() != null);
	}

	
	/**
	 * Register a new transaction synchronization for the current thread.
	 * Typically called by resource management code.
	 * <p>Note that synchronizations can implement the
	 * {@link org.springframework.core.Ordered} interface.
	 * They will be executed in an order according to their order value (if any).
	 * @param synchronization the synchronization object to register
	 * @throws IllegalStateException if transaction synchronization is not active
	 * @see org.springframework.core.Ordered
	 */
	public static void registerSynchronization(TransactionSynchronization synchronization)
			throws IllegalStateException {

		Assert.notNull(synchronization, "TransactionSynchronization must not be null");
		Set<TransactionSynchronization> synchs = synchronizations.get();
		if (synchs == null) {
			throw new IllegalStateException("Transaction synchronization is not active");
		}
		synchs.add(synchronization);
	}
	
}

Rocketmq方法封装,通过TransactionSynchronizationManager.isSynchronizationActive()判断当前方法的调用是否在事务内。

如果是,则注册一个事务同步适配器,在事务提交后发送消息。

否则直接发送。

java 复制代码
    /**
     * 事务内发送 mq时使用,强制到事务结束后发送
     */
    public SendResult sendAfterTrans(String topic, String tag, String key, String body) {
        final SendResult[] res = new SendResult[1];
        try {
            // 是否开启事务判断
            if (TransactionSynchronizationManager.isSynchronizationActive()) {
                log.debug("Mysql事务内Mq消息发送  延迟到事务提交后 waiting......");
                TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                    @Override
                    public void afterCommit() {
                        log.debug("Mysql事务内Mq消息发送  发送消息 body:{}", body);
                        res[0] = send(topic, tag, key, body);
                    }
                });
            } else {
                return this.send(topic, tag, key, body);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res[0];
    }
相关推荐
文丑颜不良啊33 分钟前
LeetCode2481~2500题目解析
java·leetcode
Flynn Liang2 小时前
同一需求三套写法:用 Spring AI、LangChain4j、AgentScope Java 各实现一个带工具调用的 RAG 助手(实战对比)
java·人工智能·大模型·架构设计·spring ai·langchain4j·agentscope
聪明的笨猪猪2 小时前
实际工程问题:AI 生成 Spring Cache(@Cacheable / @CachePut / @CacheEvict)缓存注解踩坑
java·经验分享·面试·ai编程
愿有所息2 小时前
记一次 ARM64 + JDK8 上 fastjson2 的诡异数据错乱
java
秋饼3 小时前
MCP 2026-07-28 无状态协议大改版:Spring AI 2.1 多轮往返请求与网关路由落地
java·ai·技术分享·后端开发
SL_staff4 小时前
JVS-BI 实战:业务人员如何用零代码 ELT + 可视化配置构建实时经营分析闭环
java·spring·全栈
SL_staff4 小时前
企业AI落地难?JVS-AI渐进式实践:安全可控、小切口验证、标准化沉淀与规模化复制
java·开源·aigc
这个DBA有点耶5 小时前
函数索引的“完全一致”有多苛刻:写法、字符集、类型,差一处就失效
数据库·mysql·代码规范
星恒随风5 小时前
MySQL 从零入门(三):表的约束详解
linux·服务器·数据库·笔记·mysql
SL_staff6 小时前
JVS数字底座实践:构建企业级统一内容管理平台的技术路径
java·产品