【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];
    }
相关推荐
code2cat4 分钟前
Java进阶篇之AtomicLongArray:大数累加、上限检查与溢出边界
java·开发语言
开开心心_Every9 分钟前
电脑OCR识别软件支持表格识别图片转Excel
java·开发语言·微信·计算机外设·ocr·intellij-idea·excel
弯_弯10 分钟前
企业知识库 RAG 落地:从 Demo 到生产,四条工程链路与参数级自查
android·java·javascript
rannn_11121 分钟前
JVM 垃圾回收面试题全解析:从基础到进阶
java·开发语言·jvm·后端·面试
Wang's Blog27 分钟前
Java框架 SpringCloud 快速入门: Ribbon 饥饿加载
java·spring cloud·ribbon
Mortalbreeze31 分钟前
MySQL 基础篇(六):聚合查询与分组查询
数据库·mysql
天空鸟_时光不老1 小时前
10-Agent安全隐患与SQL执行层加固
java·数据库·人工智能·sql·spring·maven·mybatis
晚风叙码2 小时前
MySQL 表的约束详解:从空属性到外键
android·数据库·mysql·adb
Nebula_g2 小时前
JavaSE加强:IO流
java·开发语言·windows·stream·javase
rannn_1113 小时前
JVM 面试题:类加载过程详解(附高频考点)
java·jvm·后端