TransactionSynchronization的invokeAfterCompletion事务源码解析

 更新时间:2023年09月11日 11:04:22   作者:codecraft  
这篇文章主要为大家介绍了TransactionSynchronization的invokeAfterCompletion事务源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下TransactionSynchronization的invokeAfterCompletion

afterCompletion

org/springframework/transaction/support/TransactionSynchronization.java

public interface TransactionSynchronization extends Flushable {
    /** Completion status in case of proper commit. */
    int STATUS_COMMITTED = 0;
    /** Completion status in case of proper rollback. */
    int STATUS_ROLLED_BACK = 1;
    /** Completion status in case of heuristic mixed completion or system errors. */
    int STATUS_UNKNOWN = 2;
    //......
    /**
     * Invoked after transaction commit. Can perform further operations right
     * <i>after</i> the main transaction has <i>successfully</i> committed.
     * <p>Can e.g. commit further operations that are supposed to follow on a successful
     * commit of the main transaction, like confirmation messages or emails.
     * <p><b>NOTE:</b> The transaction will have been committed already, but the
     * transactional resources might still be active and accessible. As a consequence,
     * any data access code triggered at this point will still "participate" in the
     * original transaction, allowing to perform some cleanup (with no commit following
     * anymore!), unless it explicitly declares that it needs to run in a separate
     * transaction. Hence: <b>Use {@code PROPAGATION_REQUIRES_NEW} for any
     * transactional operation that is called from here.</b>
     * @throws RuntimeException in case of errors; will be <b>propagated to the caller</b>
     * (note: do not throw TransactionException subclasses here!)
     */
    default void afterCommit() {
    }
    /**
     * Invoked after transaction commit/rollback.
     * Can perform resource cleanup <i>after</i> transaction completion.
     * <p><b>NOTE:</b> The transaction will have been committed or rolled back already,
     * but the transactional resources might still be active and accessible. As a
     * consequence, any data access code triggered at this point will still "participate"
     * in the original transaction, allowing to perform some cleanup (with no commit
     * following anymore!), unless it explicitly declares that it needs to run in a
     * separate transaction. Hence: <b>Use {@code PROPAGATION_REQUIRES_NEW}
     * for any transactional operation that is called from here.</b>
     * @param status completion status according to the {@code STATUS_*} constants
     * @throws RuntimeException in case of errors; will be <b>logged but not propagated</b>
     * (note: do not throw TransactionException subclasses here!)
     * @see #STATUS_COMMITTED
     * @see #STATUS_ROLLED_BACK
     * @see #STATUS_UNKNOWN
     * @see #beforeCompletion
     */
    default void afterCompletion(int status) {
    }
}
afterCompletion方法有入参status,表示事务结束时候的状态,0表示事务已提交,1表示事务已回滚,2表示事务未知;与afterCommit的一个最重要的区别是afterCompletion的异常会被捕获,不像afterCommit会抛给调用方

invokeAfterCompletion

org/springframework/transaction/support/TransactionSynchronizationUtils.java

/**
     * Actually invoke the {@code afterCompletion} methods of the
     * given Spring TransactionSynchronization objects.
     * @param synchronizations a List of TransactionSynchronization objects
     * @param completionStatus the completion status according to the
     * constants in the TransactionSynchronization interface
     * @see TransactionSynchronization#afterCompletion(int)
     * @see TransactionSynchronization#STATUS_COMMITTED
     * @see TransactionSynchronization#STATUS_ROLLED_BACK
     * @see TransactionSynchronization#STATUS_UNKNOWN
     */
    public static void invokeAfterCompletion(@Nullable List<TransactionSynchronization> synchronizations,
            int completionStatus) {
        if (synchronizations != null) {
            for (TransactionSynchronization synchronization : synchronizations) {
                try {
                    synchronization.afterCompletion(completionStatus);
                }
                catch (Throwable tsex) {
                    logger.error("TransactionSynchronization.afterCompletion threw exception", tsex);
                }
            }
        }
    }
可以看到TransactionSynchronizationUtils的invokeAfterCompletion方法会遍历synchronizations,挨个执行afterCompletion,注意这里catch了Throwable异常,进行了error级别的log

AbstractPlatformTransactionManager

org/springframework/transaction/support/AbstractPlatformTransactionManager.java

/**
     * Actually invoke the {@code afterCompletion} methods of the
     * given Spring TransactionSynchronization objects.
     * <p>To be called by this abstract manager itself, or by special implementations
     * of the {@code registerAfterCompletionWithExistingTransaction} callback.
     * @param synchronizations a List of TransactionSynchronization objects
     * @param completionStatus the completion status according to the
     * constants in the TransactionSynchronization interface
     * @see #registerAfterCompletionWithExistingTransaction(Object, java.util.List)
     * @see TransactionSynchronization#STATUS_COMMITTED
     * @see TransactionSynchronization#STATUS_ROLLED_BACK
     * @see TransactionSynchronization#STATUS_UNKNOWN
     */
    protected final void invokeAfterCompletion(List<TransactionSynchronization> synchronizations, int completionStatus) {
        TransactionSynchronizationUtils.invokeAfterCompletion(synchronizations, completionStatus);
    }
    /**
     * Trigger {@code afterCompletion} callbacks.
     * @param status object representing the transaction
     * @param completionStatus completion status according to TransactionSynchronization constants
     */
    private void triggerAfterCompletion(DefaultTransactionStatus status, int completionStatus) {
        if (status.isNewSynchronization()) {
            List<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
            TransactionSynchronizationManager.clearSynchronization();
            if (!status.hasTransaction() || status.isNewTransaction()) {
                if (status.isDebug()) {
                    logger.trace("Triggering afterCompletion synchronization");
                }
                // No transaction or new transaction for the current scope ->
                // invoke the afterCompletion callbacks immediately
                invokeAfterCompletion(synchronizations, completionStatus);
            }
            else if (!synchronizations.isEmpty()) {
                // Existing transaction that we participate in, controlled outside
                // of the scope of this Spring transaction manager -> try to register
                // an afterCompletion callback with the existing (JTA) transaction.
                registerAfterCompletionWithExistingTransaction(status.getTransaction(), synchronizations);
            }
        }
    }
AbstractPlatformTransactionManager的invokeAfterCompletion委托给了TransactionSynchronizationUtils.invokeAfterCompletion;triggerAfterCompletion主要是根据事务状态执行不同逻辑,分别是invokeAfterCompletion与registerAfterCompletionWithExistingTransaction,后者主要是JTA之类的场景,它回传的status是STATUS_UNKNOWN

小结

afterCompletion方法有入参status,表示事务结束时候的状态,0表示事务已提交,1表示事务已回滚,2表示事务未知(一般是JTA相关);与afterCommit的一个最重要的区别是afterCompletion的异常(Throwable)会被捕获,不像afterCommit会抛给调用方

doc 聊聊spring的TransactionSynchronizationAdapter

以上就是TransactionSynchronization的invokeAfterCompletion事务源码解析的详细内容,更多关于TransactionSynchronization invokeAfterCompletion的资料请关注脚本之家其它相关文章!

相关文章

  • Java常用锁synchronized和ReentrantLock的区别

    Java常用锁synchronized和ReentrantLock的区别

    这篇文章主要介绍了Java常用锁synchronized和ReentrantLock的区别,二者的功效都是相同的,但又有很多不同点,下面我们就进入文章了解具体的相关内容吧。需要的小伙伴也可以参考一下
    2022-05-05
  • Java Swing JLabel标签的使用方法

    Java Swing JLabel标签的使用方法

    这篇文章主要介绍了Java Swing JLabel标签的使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-12-12
  • Java字符串驼峰与下换线格式转换如何实现

    Java字符串驼峰与下换线格式转换如何实现

    这篇文章主要介绍了Java字符串驼峰与下换线格式转换如何实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • SpringBoot使用maven实现多环境运行和打包的操作步骤

    SpringBoot使用maven实现多环境运行和打包的操作步骤

    在开发过程中,需要不断进行环境的切换和打包部署,maven提供了多环境配置,可以方便实现不同环境的配置切换和打包,本文通过代码示例给大家介绍的非常详细,需要的朋友可以参考下
    2024-04-04
  • java如何获取10位和13位时间戳

    java如何获取10位和13位时间戳

    这篇文章主要介绍了java如何获取10位和13位时间戳问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-04-04
  • java中构造器内部调用构造器实例详解

    java中构造器内部调用构造器实例详解

    在本篇文章里小编给大家分享的是关于java中构造器内部调用构造器实例内容,需要的朋友们可以学习下。
    2020-05-05
  • 使用spring容器在初始化Bean时前和后的操作

    使用spring容器在初始化Bean时前和后的操作

    这篇文章主要介绍了使用spring容器在初始化Bean时前和后的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • Spring Bean实例的创建及构造器的挑选

    Spring Bean实例的创建及构造器的挑选

    这篇文章主要介绍了Spring Bean实例的创建及构造器的挑选,文中有非常详细的代码示例,对正在学习java的小伙伴们有很好的帮助,需要的朋友可以参考下
    2021-04-04
  • 使用MDC实现日志链路跟踪

    使用MDC实现日志链路跟踪

    这篇文章主要介绍了使用MDC实现日志链路跟踪,在微服务环境中,我们经常使用Skywalking、CAT等去实现整体请求链路的追踪,但是这个整体运维成本高,架构复杂,我们来使用MDC通过Log来实现一个轻量级的会话事务跟踪功能,下面就来看看具体的过程吧,需要的朋友可以参考一下
    2022-01-01
  • Java从零开始创建功能丰富的PDF文档

    Java从零开始创建功能丰富的PDF文档

    随着数字化办公的普及,PDF格式因其跨平台兼容性和安全性而被广泛应用于各种场景中,本文将详细介绍如何使用Java来实现PDF文档的一键生成,有需要的可以了解下
    2025-01-01

最新评论