Spring事务原理详解(看这篇就够了)

Spring事务原理详解(看这篇就够了)-mikechen

Spring事务

Spring本身并不实现事务,Spring事务的本质还是底层数据库对事务的支持,没有数据库 事务的支持,Spring事务就不会生效。

例如:使用JDBC 操作数据库,使用事务的步骤主要分为如下5步:

第一步:获取连接 Connection con = DriverManager.getConnection();

第二步:开启事务con.setAutoCommit(true/false);

第三步:执行CRUD;

第四步:提交事务/回滚事务 con.commit() / con.rollback();

第五步:关闭连接 conn.close();

采用Spring事务后,只需要 关注第三步的实现,其他的步骤都是Spring自动完成。

Spring事务的本质其实就是数据库对事务的支持,Spring只提供统一事务管理接口,具体实现都是由各数据库自己实现。

 

Spring事务使用

Spring事务管理有两种方式:编程式事务管理、声明式事务管理。

Spring事务原理详解(看这篇就够了)-mikechen

1.编程式事务

所谓编程式事务指的是通过编码方式实现事务,允许用户在代码中精确定义事务的边界。

Spring团队通常建议使用TransactionTemplate进行程序化事务管理,如下所示:

@Autowired
private TransactionTemplate transactionTemplate;
public void testTransaction() {

        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {

                try {

                    // ....  业务代码
                } catch (Exception e){
                    //回滚
                    transactionStatus.setRollbackOnly();
                }

            }
        });
}

 

2. 声明式事务

声明式事务最大的优点:就是不需要通过编程的方式管理事务,只需在需要使用的地方标注@Transactional注解,就能为该方法开启事务了。

如下所示:

@Transaction
public void insert(String userName){
    this.jdbcTemplate.update("insert into t_user (name) values (?)", userName);
}

 

Spring事务实现原理

想要了解Spring事务的实现原理,一个绕不开的点就是Spring AOP,因为事务就是依靠Spring AOP实现的。

@EnableTransactionManagement是开启注解式事务的事务,如果注解式事务真的有玄机,那么@EnableTransactionManagement就是我们揭开秘密的突破口。

@EnableTransactionManagement注解源码如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(TransactionManagementConfigurationSelector.class)
public @interface EnableTransactionManagement {

    /**
     * 用来表示默认使用JDK Dynamic Proxy还是CGLIB Proxy
     */
    boolean proxyTargetClass() default false;

    /**
     * 表示以Proxy-based方式实现AOP还是以Weaving-based方式实现AOP
     */
    AdviceMode mode() default AdviceMode.PROXY;

    /**
     * 顺序
     */
    int order() default Ordered.LOWEST_PRECEDENCE;

}

@EnableTransactionManagement注解,主要通过@Import引入了另一个配置TransactionManagentConfigurationSelector。

在 Spring中Selector通常都是用来选择一些Bean,向容器注册:AutoProxyRegistrar、ProxyTransactionManagementConfiguration两个Bean。

ProxyTransactionManagementConfiguration是一个配置类,实现类主要是TransactionInterceptor,这里会涉及Spring AOP实现切面逻辑织入。

要实现AOP需要明确两个点:

1)定义切点:需要在哪里做增强?

2)定义增强逻辑:需要做什么样的增强逻辑?

​ 如果对于这两点,Spring主要通过事务代理管理配置类:ProxyTransactionManagementConfiguration来实现的。

首先看下核心调用接口TransactionInterceptor实现的invoke()方法的源码:

@Override
@Nullable
public Object invoke(final MethodInvocation invocation) throws Throwable {
    // 获取需要织入事务逻辑的目标类
    Class<?> targetClass = (invocation.getThis() != null ? 
        AopUtils.getTargetClass(invocation.getThis()) : null);

    // 进行事务逻辑的织入
    return invokeWithinTransaction(invocation.getMethod(), targetClass, 
        invocation::proceed);
}

在 invokeWithinTransaction 中会调用 createTransactionIfNecessary 方法:

protected TransactionInfo createTransactionIfNecessary(
    @Nullable PlatformTransactionManager tm, @Nullable TransactionAttribute txAttr, 
    final String joinpointIdentification) {
    // 如果TransactionAttribute的名称为空,则创建一个代理的TransactionAttribute,
    // 并且将其名称设置为需要织入事务的方法的名称
    if (txAttr != null && txAttr.getName() == null) {
        txAttr = new DelegatingTransactionAttribute(txAttr) {
            @Override
            public String getName() {
                return joinpointIdentification;
            }
        };
    }

    TransactionStatus status = null;
    if (txAttr != null) {
        if (tm != null) {
            // 如果事务属性不为空,并且TransactionManager都存在,
            // 则通过TransactionManager获取当前事务状态的对象
            status = tm.getTransaction(txAttr);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Skipping transactional joinpoint [" 
                     + joinpointIdentification 
                     + "] because no transaction manager has been configured");
            }
        }
    }
    
    // 将当前事务属性和事务状态封装为一个TransactionInfo,这里主要做的工作是将事务属性绑定到当前线程
    return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}

这里对事务的创建,首先会判断封装事务属性的对象名称是否为空,如果不为空,则以目标方法的标识符作为其名称,然后通过TransactionManager创建事务。

如下是TransactionManager.getTransaction()方法的源码:

@Override
    public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
            throws TransactionException {

        //如果TransactionDefinition为空则使用默认配置
        TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());

        Object transaction = doGetTransaction();
        boolean debugEnabled = logger.isDebugEnabled();

        if (isExistingTransaction(transaction)) {
            //如果有存在的事务,则处理存在的事物
            return handleExistingTransaction(def, transaction, debugEnabled);
        }

        // 判断事务是否超时
        if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
            throw new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout());
        }

        // 使用PROPAGATION_MANDATORY这个级别,没有可用的事务则抛异常
        if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
            throw new IllegalTransactionStateException(
                    "No existing transaction found for transaction marked with propagation 'mandatory'");
        }
        else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
                def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
                def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
            SuspendedResourcesHolder suspendedResources = suspend(null);
            if (debugEnabled) {
                logger.debug("Creating new transaction with name [" + def.getName() + "]: " + def);
            }
            try {
        //根据隔离级别开始事务
                return startTransaction(def, transaction, debugEnabled, suspendedResources);
            }
            catch (RuntimeException | Error ex) {
                resume(null, suspendedResources);
                throw ex;
            }
        }
        else {
            // Create "empty" transaction: no actual transaction, but potentially synchronization.
            if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
                logger.warn("Custom isolation level specified but no actual transaction initiated; " +
                        "isolation level will effectively be ignored: " + def);
            }
            boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
            return prepareTransactionStatus(def, null, true, newSynchronization, debugEnabled, null);
        }
    }

startTransaction 会调用 DataSourceTransactionManager 的 doBegin 方法设置当前连接为手动提交事务。

@Override
    protected void doBegin(Object transaction, TransactionDefinition definition) {
        DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
        Connection con = null;

        try {
      //获取数据库连接
            if (!txObject.hasConnectionHolder() ||
                    txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
                Connection newCon = obtainDataSource().getConnection();
                if (logger.isDebugEnabled()) {
                    logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
                }
                txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
            }

            txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
            con = txObject.getConnectionHolder().getConnection();

            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            txObject.setPreviousIsolationLevel(previousIsolationLevel);
            txObject.setReadOnly(definition.isReadOnly());

            //如果连接是自动提交,则设置成手动
            if (con.getAutoCommit()) {
                txObject.setMustRestoreAutoCommit(true);
                if (logger.isDebugEnabled()) {
                    logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
                }
        //这里会和数据库通信
                con.setAutoCommit(false);
            }

            prepareTransactionalConnection(con, definition);
            txObject.getConnectionHolder().setTransactionActive(true);

            int timeout = determineTimeout(definition);
            if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
                txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
            }

            // Bind the connection holder to the thread.
            if (txObject.isNewConnectionHolder()) {
                TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
            }
        }

        catch (Throwable ex) {
            if (txObject.isNewConnectionHolder()) {
                DataSourceUtils.releaseConnection(con, obtainDataSource());
                txObject.setConnectionHolder(null, false);
            }
            throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
        }
    }

再看回 org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction 方法,这里显示了 aop 如何处理事务

if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
        
            //获取事务
            TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);

            Object retVal;
         	try {
                //触发后面的拦截器和方法本身
                retVal = invocation.proceedWithInvocation();
            }
            catch (Throwable ex) {
                // 捕获异常处理回滚
                completeTransactionAfterThrowing(txInfo, ex);
                throw ex;
            }
            finally {
        //重置threadLocal中事务状态
                cleanupTransactionInfo(txInfo);
            }
            //省略
            ...
            return retVal;
        }

再看一下 completeTransactionAfterThrowing 方法,如果是需要回滚的异常则执行回滚,否则执行提交

protected void completeTransactionAfterThrowing(@Nullable TransactionInfo txInfo, Throwable ex) {
        if (txInfo != null && txInfo.getTransactionStatus() != null) {
            if (logger.isTraceEnabled()) {
                logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() +
                        "] after exception: " + ex);
            }
            //需要回滚的异常
            if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
                try {
                    //执行回滚
                    txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
                }
                catch (TransactionSystemException ex2) {
                    logger.error("Application exception overridden by rollback exception", ex);
                    ex2.initApplicationException(ex);
                    throw ex2;
                }
                catch (RuntimeException | Error ex2) {
                    logger.error("Application exception overridden by rollback exception", ex);
                    throw ex2;
                }
            }
            else {
                try {
                    //提交
                    txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
                }
                catch (TransactionSystemException ex2) {
                    logger.error("Application exception overridden by commit exception", ex);
                    ex2.initApplicationException(ex);
                    throw ex2;
                }
                catch (RuntimeException | Error ex2) {
                    logger.error("Application exception overridden by commit exception", ex);
                    throw ex2;
                }
            }
        }
    }

 

Spring事务原理总结

Spring事务的本质其实就是Spring AOP和数据库事务,Spring 将数据库的事务操作提取为 切面,通过AOP在方法执行前后增加数据库事务操作。

 

作者简介

陈睿|mikechen,10年+大厂架构经验,BAT资深面试官,就职于阿里巴巴、淘宝、百度等一线互联网大厂。

👇阅读更多mikechen架构文章👇

阿里架构 |双11秒杀 |分布式架构 |负载均衡 |单点登录 |微服务 |云原生 |高并发 |架构师

以上

关注作者「mikechen」公众号,获取更多技术干货!

后台回复架构,即可获取《阿里架构师进阶专题全部合集》,后台回复面试即可获取《史上最全阿里Java面试题总结

评论交流
    说说你的看法