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进行程序化事务管理,如下所示:

  1. @Autowired
  2. private TransactionTemplate transactionTemplate;
  3. public void testTransaction() {
  4.  
  5. transactionTemplate.execute(new TransactionCallbackWithoutResult() {
  6. @Override
  7. protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
  8.  
  9. try {
  10.  
  11. // .... 业务代码
  12. } catch (Exception e){
  13. //回滚
  14. transactionStatus.setRollbackOnly();
  15. }
  16.  
  17. }
  18. });
  19. }

 

2. 声明式事务

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

如下所示:

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

 

Spring事务实现原理

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

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

@EnableTransactionManagement注解源码如下:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Import(TransactionManagementConfigurationSelector.class)
  5. public @interface EnableTransactionManagement {
  6.  
  7. /**
  8. * 用来表示默认使用JDK Dynamic Proxy还是CGLIB Proxy
  9. */
  10. boolean proxyTargetClass() default false;
  11.  
  12. /**
  13. * 表示以Proxy-based方式实现AOP还是以Weaving-based方式实现AOP
  14. */
  15. AdviceMode mode() default AdviceMode.PROXY;
  16.  
  17. /**
  18. * 顺序
  19. */
  20. int order() default Ordered.LOWEST_PRECEDENCE;
  21.  
  22. }

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

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

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

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

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

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

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

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

  1. @Override
  2. @Nullable
  3. public Object invoke(final MethodInvocation invocation) throws Throwable {
  4. // 获取需要织入事务逻辑的目标类
  5. Class<?> targetClass = (invocation.getThis() != null ?
  6. AopUtils.getTargetClass(invocation.getThis()) : null);
  7.  
  8. // 进行事务逻辑的织入
  9. return invokeWithinTransaction(invocation.getMethod(), targetClass,
  10. invocation::proceed);
  11. }

在 invokeWithinTransaction 中会调用 createTransactionIfNecessary 方法:

  1. protected TransactionInfo createTransactionIfNecessary(
  2. @Nullable PlatformTransactionManager tm, @Nullable TransactionAttribute txAttr,
  3. final String joinpointIdentification) {
  4. // 如果TransactionAttribute的名称为空,则创建一个代理的TransactionAttribute,
  5. // 并且将其名称设置为需要织入事务的方法的名称
  6. if (txAttr != null && txAttr.getName() == null) {
  7. txAttr = new DelegatingTransactionAttribute(txAttr) {
  8. @Override
  9. public String getName() {
  10. return joinpointIdentification;
  11. }
  12. };
  13. }
  14.  
  15. TransactionStatus status = null;
  16. if (txAttr != null) {
  17. if (tm != null) {
  18. // 如果事务属性不为空,并且TransactionManager都存在,
  19. // 则通过TransactionManager获取当前事务状态的对象
  20. status = tm.getTransaction(txAttr);
  21. } else {
  22. if (logger.isDebugEnabled()) {
  23. logger.debug("Skipping transactional joinpoint ["
  24. + joinpointIdentification
  25. + "] because no transaction manager has been configured");
  26. }
  27. }
  28. }
  29. // 将当前事务属性和事务状态封装为一个TransactionInfo,这里主要做的工作是将事务属性绑定到当前线程
  30. return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
  31. }

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

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

  1. @Override
  2. public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition)
  3. throws TransactionException {
  4.  
  5. //如果TransactionDefinition为空则使用默认配置
  6. TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());
  7.  
  8. Object transaction = doGetTransaction();
  9. boolean debugEnabled = logger.isDebugEnabled();
  10.  
  11. if (isExistingTransaction(transaction)) {
  12. //如果有存在的事务,则处理存在的事物
  13. return handleExistingTransaction(def, transaction, debugEnabled);
  14. }
  15.  
  16. // 判断事务是否超时
  17. if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
  18. throw new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout());
  19. }
  20.  
  21. // 使用PROPAGATION_MANDATORY这个级别,没有可用的事务则抛异常
  22. if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
  23. throw new IllegalTransactionStateException(
  24. "No existing transaction found for transaction marked with propagation 'mandatory'");
  25. }
  26. else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
  27. def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
  28. def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
  29. SuspendedResourcesHolder suspendedResources = suspend(null);
  30. if (debugEnabled) {
  31. logger.debug("Creating new transaction with name [" + def.getName() + "]: " + def);
  32. }
  33. try {
  34. //根据隔离级别开始事务
  35. return startTransaction(def, transaction, debugEnabled, suspendedResources);
  36. }
  37. catch (RuntimeException | Error ex) {
  38. resume(null, suspendedResources);
  39. throw ex;
  40. }
  41. }
  42. else {
  43. // Create "empty" transaction: no actual transaction, but potentially synchronization.
  44. if (def.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
  45. logger.warn("Custom isolation level specified but no actual transaction initiated; " +
  46. "isolation level will effectively be ignored: " + def);
  47. }
  48. boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
  49. return prepareTransactionStatus(def, null, true, newSynchronization, debugEnabled, null);
  50. }
  51. }

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

  1. @Override
  2. protected void doBegin(Object transaction, TransactionDefinition definition) {
  3. DataSourceTransactionObject txObject = (DataSourceTransactionObject) transaction;
  4. Connection con = null;
  5.  
  6. try {
  7. //获取数据库连接
  8. if (!txObject.hasConnectionHolder() ||
  9. txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
  10. Connection newCon = obtainDataSource().getConnection();
  11. if (logger.isDebugEnabled()) {
  12. logger.debug("Acquired Connection [" + newCon + "] for JDBC transaction");
  13. }
  14. txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
  15. }
  16.  
  17. txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
  18. con = txObject.getConnectionHolder().getConnection();
  19.  
  20. Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
  21. txObject.setPreviousIsolationLevel(previousIsolationLevel);
  22. txObject.setReadOnly(definition.isReadOnly());
  23.  
  24. //如果连接是自动提交,则设置成手动
  25. if (con.getAutoCommit()) {
  26. txObject.setMustRestoreAutoCommit(true);
  27. if (logger.isDebugEnabled()) {
  28. logger.debug("Switching JDBC Connection [" + con + "] to manual commit");
  29. }
  30. //这里会和数据库通信
  31. con.setAutoCommit(false);
  32. }
  33.  
  34. prepareTransactionalConnection(con, definition);
  35. txObject.getConnectionHolder().setTransactionActive(true);
  36.  
  37. int timeout = determineTimeout(definition);
  38. if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
  39. txObject.getConnectionHolder().setTimeoutInSeconds(timeout);
  40. }
  41.  
  42. // Bind the connection holder to the thread.
  43. if (txObject.isNewConnectionHolder()) {
  44. TransactionSynchronizationManager.bindResource(obtainDataSource(), txObject.getConnectionHolder());
  45. }
  46. }
  47.  
  48. catch (Throwable ex) {
  49. if (txObject.isNewConnectionHolder()) {
  50. DataSourceUtils.releaseConnection(con, obtainDataSource());
  51. txObject.setConnectionHolder(null, false);
  52. }
  53. throw new CannotCreateTransactionException("Could not open JDBC Connection for transaction", ex);
  54. }
  55. }

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

  1. if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
  2. //获取事务
  3. TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);
  4.  
  5. Object retVal;
  6. try {
  7. //触发后面的拦截器和方法本身
  8. retVal = invocation.proceedWithInvocation();
  9. }
  10. catch (Throwable ex) {
  11. // 捕获异常处理回滚
  12. completeTransactionAfterThrowing(txInfo, ex);
  13. throw ex;
  14. }
  15. finally {
  16. //重置threadLocal中事务状态
  17. cleanupTransactionInfo(txInfo);
  18. }
  19. //省略
  20. ...
  21. return retVal;
  22. }

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

  1. protected void completeTransactionAfterThrowing(@Nullable TransactionInfo txInfo, Throwable ex) {
  2. if (txInfo != null && txInfo.getTransactionStatus() != null) {
  3. if (logger.isTraceEnabled()) {
  4. logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() +
  5. "] after exception: " + ex);
  6. }
  7. //需要回滚的异常
  8. if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
  9. try {
  10. //执行回滚
  11. txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());
  12. }
  13. catch (TransactionSystemException ex2) {
  14. logger.error("Application exception overridden by rollback exception", ex);
  15. ex2.initApplicationException(ex);
  16. throw ex2;
  17. }
  18. catch (RuntimeException | Error ex2) {
  19. logger.error("Application exception overridden by rollback exception", ex);
  20. throw ex2;
  21. }
  22. }
  23. else {
  24. try {
  25. //提交
  26. txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
  27. }
  28. catch (TransactionSystemException ex2) {
  29. logger.error("Application exception overridden by commit exception", ex);
  30. ex2.initApplicationException(ex);
  31. throw ex2;
  32. }
  33. catch (RuntimeException | Error ex2) {
  34. logger.error("Application exception overridden by commit exception", ex);
  35. throw ex2;
  36. }
  37. }
  38. }
  39. }

 

Spring事务原理总结

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

 

关注「mikechen」,十余年BAT架构经验倾囊相授!

评论交流
    说说你的看法
欢迎您,新朋友,感谢参与互动!