【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];
    }
相关推荐
IT规划师5 分钟前
百亿数据写入 MySQL:空间降维 × IO 降维 × 工程兜底
mysql·sqlsugar·.net10
荣码8 分钟前
长上下文与大文档处理:200页PDF怎么喂给AI,我踩了4个坑
java·python
极限挑战哥39 分钟前
共享电单车联营平台分账架构实践:二清合规与自动分账零人工方案
java·大数据·人工智能·微信小程序·架构·微信公众平台
皮皮林5511 小时前
比 VMware 更快,更轻的虚拟机,横空出世!
java
Thomas.Sir1 小时前
第13课:MyBatis-Plus整合SpringBoot4.x,分页、条件查询、逻辑删除实战
java·spring boot
meiying88382 小时前
多快递公司快递单号批量查询接口怎么对接?Python 聚合查询实现
java·大数据·python
古法安卓2 小时前
Android-GPU压测工具
android·java·android studio
数据库小学妹2 小时前
MySQL NULL陷阱:NOT IN、三值逻辑与NOT EXISTS
数据库·后端·mysql
枫昕柚2 小时前
MySQL 建库命令详解:从 CREATE DATABASE 到create table
数据库·mysql
SL_staff2 小时前
10人团队如何用轻量私有化文档平台实现知识复用提效?技术视角拆解B/S架构下的协作闭环
java·开源·全栈