码迷,mamicode.com
首页 > 编程语言 > 详细

spring tx——TransactionManger

时间:2020-07-01 20:04:44      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:set   开启   value   bug   abstract   存在   标记   poi   tee   

TransactionDefinition——事务定义

定义事务属性,包括传播级别、隔离级别、名称、超时、只读等

技术图片

TransactionStatus——事务状态

事务状态,包含事务对象(jdbc为DataSourceTransactionObject),是否新事务、是否新同步对象、是否只读、是否回滚、是否完成、事务中断对象(SuspendedResourcesHolder实现事务中断,保存中断事务的信息)、保存点对象(jdbc为Savepoint,实现嵌套事务)

技术图片

DataSourceTransactionObject——事务对象

jdbc中事务对象。

技术图片

持有一个ConnectionHolder对象,而ConnectionHolder持有Connection对象。

技术图片

SuspendedResourcesHolder——中断事务对象

用于实现事务挂起,持有一个中断事务suspendedResources(jdbc为ConnectionHolder),中断同步对象集合suspendedSynchronizations。

技术图片

SavePoint——保存点

保存点用于实现嵌套事务,只有jdbc才有

TransactionManger——事务管理器

技术图片

AbstractPlatformTransactionManager:实现事务的获取、提交、回滚等主要逻辑

传播级别——Propagation

  1. PROPAGATION_REQUIRED:支持当前事务,没有事务开启事务
  2. PROPAGATION_SUPPORTS:支持当前事务,没有事务非事务运行
  3. PROPAGATION_MANDATORY:支持当前事务,没有事务报错
  4. PROPAGATION_REQUIRES_NEW:有事务挂起事务,新建事务
  5. PROPAGATION_NOT_SUPPORTED:有事务挂起事务,非事务执行
  6. PROPAGATION_NEVER:有事务报错
  7. PROPAGATION_NESTED:嵌套事务,外层事务回滚,内层也回滚

getTransaction——获取事务

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

		TransactionDefinition def = (definition != null ? definition : TransactionDefinition.withDefaults());
		
    	//1.封装transaction对象并获取当前事务的ConnectionHolder
		Object transaction = doGetTransaction();
		
    	//2.当前存在事务,根据事务传播级别处理
		if (isExistingTransaction(transaction)) {
			return handleExistingTransaction(def, transaction, debugEnabled);
		}

		if (def.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
			throw new InvalidTimeoutException("Invalid transaction timeout", def.getTimeout());
		}
		
    	//3.当前不存在事务,根据不同事务传播级别处理
    	//3.1. 如果传播级别是PROPAGATION_MANDATORY,不存在事务报错
		if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
			throw new IllegalTransactionStateException(
					"No existing transaction found for transaction marked with propagation ‘mandatory‘");
		}
    	//3.2. 如果传播级别是PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW、PROPAGATION_NESTED
		else if (def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
				def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
				def.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
            //3.2.1. 中断事务同步管理器中注册的同步对象,封装中断事务对象
			SuspendedResourcesHolder suspendedResources = suspend(null);
			try {
                //3.2.2. 开启新事务
				return startTransaction(def, transaction, debugEnabled, suspendedResources);
			}
			catch (RuntimeException | Error ex) {
                //3.2.3. 开启新事务失败,重启中断事务对象中的同步对象
				resume(null, suspendedResources);
				throw ex;
			}
		}
    	//3.3. 其他传播级别,以非事务执行代码,但还是封装TransactionStatus返回
		else {
			boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
			return prepareTransactionStatus(def, null, true, newSynchronization, debugEnabled, null);
		}
	}

private TransactionStatus handleExistingTransaction(
			TransactionDefinition definition, Object transaction, boolean debugEnabled)
			throws TransactionException {

    	//传播级别为PROPAGATION_NEVER抛错异常
		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
			throw new IllegalTransactionStateException(
					"Existing transaction found for transaction marked with propagation ‘never‘");
		}
		
    	//传播级别为PROPAGATION_NOT_SUPPORTED,中断当前事务,以非事务执行
		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NOT_SUPPORTED) {
			if (debugEnabled) {
				logger.debug("Suspending current transaction");
			}
			Object suspendedResources = suspend(transaction);
			boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
			return prepareTransactionStatus(
					definition, null, false, newSynchronization, debugEnabled, suspendedResources);
		}
		
    	//传播级别为PROPAGATION_REQUIRES_NEW,中断当前事务,开启新事务
		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW) {
			if (debugEnabled) {
				logger.debug("Suspending current transaction, creating new transaction with name [" +
						definition.getName() + "]");
			}
			SuspendedResourcesHolder suspendedResources = suspend(transaction);
			try {
				return startTransaction(definition, transaction, debugEnabled, suspendedResources);
			}
			catch (RuntimeException | Error beginEx) {
				resumeAfterBeginException(transaction, suspendedResources, beginEx);
				throw beginEx;
			}
		}
		
    	//传播级别为PROPAGATION_NESTED,jdbc处理为在当前事务上创建一个保存点
		if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
			if (!isNestedTransactionAllowed()) {
				throw new NestedTransactionNotSupportedException(
						"Transaction manager does not allow nested transactions by default - " +
						"specify ‘nestedTransactionAllowed‘ property with value ‘true‘");
			}
			if (debugEnabled) {
				logger.debug("Creating nested transaction with name [" + definition.getName() + "]");
			}
			if (useSavepointForNestedTransaction()) {
				DefaultTransactionStatus status =
						prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
				status.createAndHoldSavepoint();
				return status;
			}
			else {
				// JTA事务的处理
				return startTransaction(definition, transaction, debugEnabled, null);
			}
		}

		// 传播级别为PROPAGATION_SUPPORTS、PROPAGATION_REQUIRED以当前事务执行
		//省略代码。。。
    
		boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
		return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
	}

技术图片

commit——提交事务

public final void commit(TransactionStatus status) throws TransactionException {
		//1.TransactionStatus设置了回滚,执行回滚操作
		DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
		if (defStatus.isLocalRollbackOnly()) {
			if (defStatus.isDebug()) {
				logger.debug("Transactional code has requested rollback");
			}
			processRollback(defStatus, false);
			return;
		}
		//2.TransactionStatus的ConnectionHolder设置了回滚,执行回滚操作
		if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
			if (defStatus.isDebug()) {
				logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
			}
			processRollback(defStatus, true);
			return;
		}
		//3.执行提交操作
		processCommit(defStatus);
	}

processCommit方法:

private void processCommit(DefaultTransactionStatus status) throws TransactionException {
		try {
			boolean beforeCompletionInvoked = false;

			try {
				boolean unexpectedRollback = false;
				prepareForCommit(status);
                //触发TransactionSynchronization的beforeCommit和beforeCompletion
				triggerBeforeCommit(status);
				triggerBeforeCompletion(status);
				beforeCompletionInvoked = true;
				
                //有保存点,即嵌套事务,释放保存点
				if (status.hasSavepoint()) {
					if (status.isDebug()) {
						logger.debug("Releasing transaction savepoint");
					}
					unexpectedRollback = status.isGlobalRollbackOnly();
					status.releaseHeldSavepoint();
				}
                //如果是事务最外层,提交事务
				else if (status.isNewTransaction()) {
					if (status.isDebug()) {
						logger.debug("Initiating transaction commit");
					}
					unexpectedRollback = status.isGlobalRollbackOnly();
					doCommit(status);
				}
                //默认为false
				else if (isFailEarlyOnGlobalRollbackOnly()) {
					unexpectedRollback = status.isGlobalRollbackOnly();
				}

				if (unexpectedRollback) {
					throw new UnexpectedRollbackException(
							"Transaction silently rolled back because it has been marked as rollback-only");
				}
			}
			catch (UnexpectedRollbackException ex) {
				// can only be caused by doCommit
                //触发TransactionSynchronization的afterCompletion
				triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);
				throw ex;
			}
			catch (TransactionException ex) {
				// can only be caused by doCommit
                //默认为false
				if (isRollbackOnCommitFailure()) {
					doRollbackOnCommitException(status, ex);
				}
				else {
                    //触发TransactionSynchronization的afterCompletion
					triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
				}
				throw ex;
			}
			catch (RuntimeException | Error ex) {
                //是否触发过TransactionSynchronization的beforeCompletion
				if (!beforeCompletionInvoked) {
					triggerBeforeCompletion(status);
				}
                //回滚事务
				doRollbackOnCommitException(status, ex);
				throw ex;
			}

			//触发TransactionSynchronization的afterCommit和afterCompletion
			try {
				triggerAfterCommit(status);
			}
			finally {
				triggerAfterCompletion(status, TransactionSynchronization.STATUS_COMMITTED);
			}

		}
		finally {
            //有中断事务恢复中断事务,没有重置TransactionSynchronizationManager
			cleanupAfterCompletion(status);
		}
	}

rollback——回滚事务

public final void rollback(TransactionStatus status) throws TransactionException {
		DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
		processRollback(defStatus, false);
	}

processRollback方法:

private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
		try {
			boolean unexpectedRollback = unexpected;

			try {
                //触发TransactionSynchronization的beforeCompletion
				triggerBeforeCompletion(status);
				
                //有保存点,即嵌套事务,回滚到保存点
				if (status.hasSavepoint()) {
					if (status.isDebug()) {
						logger.debug("Rolling back transaction to savepoint");
					}
					status.rollbackToHeldSavepoint();
				}
                //如果是事务最外层,回滚事务
				else if (status.isNewTransaction()) {
					if (status.isDebug()) {
						logger.debug("Initiating transaction rollback");
					}
					doRollback(status);
				}
				else {
					// 如果事务标记为回滚,将ConnectionHolder标记为回滚
					if (status.hasTransaction()) {
						if (status.isLocalRollbackOnly() || isGlobalRollbackOnParticipationFailure()) {
							doSetRollbackOnly(status);
						}
					}
					// Unexpected rollback only matters here if we‘re asked to fail early
					if (!isFailEarlyOnGlobalRollbackOnly()) {
						unexpectedRollback = false;
					}
				}
			}
			catch (RuntimeException | Error ex) {
                //触发TransactionSynchronization的afterCompletion
				triggerAfterCompletion(status, TransactionSynchronization.STATUS_UNKNOWN);
				throw ex;
			}

            //触发TransactionSynchronization的afterCompletion
			triggerAfterCompletion(status, TransactionSynchronization.STATUS_ROLLED_BACK);

			// Raise UnexpectedRollbackException if we had a global rollback-only marker
			if (unexpectedRollback) {
				throw new UnexpectedRollbackException(
						"Transaction rolled back because it has been marked as rollback-only");
			}
		}
		finally {
            //有中断事务恢复中断事务,没有重置TransactionSynchronizationManager
			cleanupAfterCompletion(status);
		}
	}

spring tx——TransactionManger

标签:set   开启   value   bug   abstract   存在   标记   poi   tee   

原文地址:https://www.cnblogs.com/wuweishuo/p/13221009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!