写在最后
为了这次面试,也收集了很多的面试题!
以下是部分面试题截图
//【标记2】执行方法,这是一个环绕通知,通常会导致目标对象被调用
retVal = invocation.proceedWithInvocation();
}
catch (Throwable ex) {
// target invocation exception
//回滚事务:AfterThrowing
completeTransactionAfterThrowing(txInfo, ex);
throw ex;
}
finally {
//清理事务
cleanupTransactionInfo(txInfo);
}
//AfterReturning:后置通知,提交事务
commitTransactionAfterReturning(txInfo);
return retVal;
}
else {
final ThrowableHolder throwableHolder = new ThrowableHolder();
// It’s a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in.
try {
Object result = ((CallbackPreferringPlatformTransactionManager) tm).execute(txAttr, status -> {
TransactionInfo txInfo = prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
try {
return invocation.proceedWithInvocation();
}
catch (Throwable ex) {
if (txAttr.rollbackOn(ex)) {
// A RuntimeException: will lead to a rollback.
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
else {
throw new ThrowableHolderException(ex);
}
}
else {
// A normal return value: will lead to a commit.
throwableHolder.throwable = ex;
return null;
}
}
finally {
cleanupTransactionInfo(txInfo);
}
});
// Check result state: It might indicate a Throwable to rethrow.
if (throwableHolder.throwable != null) {
throw throwableHolder.throwable;
}
return result;
}
catch (ThrowableHolderException ex) {
throw ex.getCause();
}
catch (TransactionSystemException ex2) {
if (throwableHolder.throwable != null) {
logger.error(“Application exception overridden by commit exception”, throwableHolder.throwable);
ex2.initApplicationException(throwableHolder.throwable);
}
throw ex2;
}
catch (Throwable ex2) {
if (throwableHolder.throwable != null) {
logger.error(“Application exception overridden by commit exception”, throwableHolder.throwable);
}
throw ex2;
}
}
}
上面方法是事务处理的宏观流程,支持编程时和声明式的事务处理,这里是使用了模板模式,细节交给子类去实现,这里我们总结一下上面方法的流程
-
获取事务属性源TransactionAttributeSource 在上一章节有说道该类
-
加载TransactionManager 事务管理器
-
对声明式或者编程式的事务处理
-
创建 TransactionInfo 事务信息对象,其中包括事务管理器(transactionManager),事务属性(transactionAttribute),方法唯一标识(joinpointIdentification),事务状态(transactionStatus)
-
执行目标方法:invocation.proceedWithInvocation
-
出现异常,则回滚事务:completeTransactionAfterThrowing,默认是对RuntimeException异常回滚
-
清理事务信息:cleanupTransactionInfo
-
提交事务:commitTransactionAfterReturning
下面来分析具体的每个步骤流程
创建事务信息:createTransactionIfNecessary
createTransactionIfNecessary 是事务流程中的第一个方法,目的是根据给定的 TransactionAttribute 创建一个事务,其中包括事务实例的创建,事务传播行为处理,开启事务等。
protected TransactionInfo createTransactionIfNecessary(@Nullable PlatformTransactionManager tm,
@Nullable TransactionAttribute txAttr, final String joinpointIdentification) {
//如果未指定名称,则应用方法标识作为事务名称
// If no name specified, apply method identification as transaction name.
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) {
//根据TransactionAttribute 事务属性创建一个事务状态对象
status = tm.getTransaction(txAttr);
}
else {
if (logger.isDebugEnabled()) {
logger.debug(“Skipping transactional joinpoint [” + joinpointIdentification +
“] because no transaction manager has been configured”);
}
}
}
return prepareTransactionInfo(tm, txAttr, joinpointIdentification, status);
}
获取事务状态:tm.getTransaction
见:AbstractPlatformTransactionManager#getTransaction
@Override
public final TransactionStatus getTransaction(@Nullable TransactionDefinition definition) throws TransactionException {
//开启一个事务,创建了一个DataSourceTransactionObject对象,其中绑定了ConnectionHolder
Object transaction = doGetTransaction();
// Cache debug flag to avoid repeated checks.
boolean debugEnabled = logger.isDebugEnabled();
if (definition == null) {
// Use defaults if no transaction definition given.
definition = new DefaultTransactionDefinition();
}
//判断是否已经存在事务,会进行事务传播机制的判断
//判断连接不为空且连接(connectionHolder)中的 transactionActive 不为空
if (isExistingTransaction(transaction)) {
//如果存在事务,走这里
// Existing transaction found -> check propagation behavior to find out how to behave.
return handleExistingTransaction(definition, transaction, debugEnabled);
}
//事务超时时间判断
// Check definition settings for new transaction.
if (definition.getTimeout() < TransactionDefinition.TIMEOUT_DEFAULT) {
throw new InvalidTimeoutException(“Invalid transaction timeout”, definition.getTimeout());
}
//【PROPAGATION_MANDATORY处理】 如果当前事务不存在,PROPAGATION_MANDATORY要求必须已有事务,则抛出异常
// No existing transaction found -> check propagation behavior to find out how to proceed.
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_MANDATORY) {
throw new IllegalTransactionStateException(
“No existing transaction found for transaction marked with propagation ‘mandatory’”);
}
//【如果没有事务,对于下面三种事务传播行为都需要新开事务】
else if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRED ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_REQUIRES_NEW ||
definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NESTED) {
//这三种事务传播机制都需要新开事务,先挂起事务
SuspendedResourcesHolder suspendedResources = suspend(null);
if (debugEnabled) {
logger.debug(“Creating new transaction with name [” + definition.getName() + "]: " + definition);
}
try {
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
//创建一个新的TransactionStatus
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
//开始事务,创建一个DataSourceTransactionObject
//设置 ConnectionHolder,设置隔离级别、设置timeout, 切换事务手动提交
//如果是新连接,绑定到当前线程
doBegin(transaction, definition);
//针对当期线程的新事务同步设置
prepareSynchronization(status, definition);
return status;
}
catch (RuntimeException | Error ex) {
resume(null, suspendedResources);
throw ex;
}
}
else {
// Create “empty” transaction: no actual transaction, but potentially synchronization.
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT && logger.isWarnEnabled()) {
logger.warn("Custom isolation level specified but no actual transaction initiated; " +
"isolation level will effectively be ignored: " + definition);
}
boolean newSynchronization = (getTransactionSynchronization() == SYNCHRONIZATION_ALWAYS);
//创建一个newTransactionStatus
return prepareTransactionStatus(definition, null, true, newSynchronization, debugEnabled, null);
}
}
该方法主要做了如下事情:
-
开启一个事务 创建了一个DataSourceTransactionObject 事务实例对象,其中绑定了ConnectionHolder,ConnectionHolder底层是ThreadLocal保存了当前线程的数据库连接信息。
-
如果当前线程存在事务,则转向嵌套事务的处理。
-
校验事务超时时间
-
如果事务传播机制是 PROPAGATION_MANDATORY ,如果不存在事务就抛异常
-
创建一个新的TransactionStatus:DefaultTransactionStatus。
-
完善事务信息设置ConnectionHolder、设置隔离级别、设置timeout,连接绑定到当前线程。
回顾一下事务传播行为:
| 事务传播行为类型 | 说明 |
| — | — |
| PROPAGATION_REQUIRED | 如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。这是最常见的选择。 |
| PROPAGATION_SUPPORTS | 支持当前事务,如果当前没有事务,就以非事务方式执行。 |
| PROPAGATION_MANDATORY | 使用当前的事务,如果当前没有事务,就抛出异常。 |
| PROPAGATION_REQUIRES_NEW | 新建事务,如果当前存在事务,把当前事务挂起。 |
| PROPAGATION_NOT_SUPPORTED | 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。 |
| PROPAGATION_NEVER | 以非事务方式执行,如果当前存在事务,则抛出异常。 |
| PROPAGATION_NESTED | 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作。 |
处理嵌套事务 :handleExistingTransaction
//为现有事务创建 TransactionStatus。
private TransactionStatus handleExistingTransaction(
TransactionDefinition definition, Object transaction, boolean debugEnabled)
throws TransactionException {
//以非事务方式执行,如果当前存在事务,则抛出异常。
if (definition.getPropagationBehavior() == TransactionDefinition.PROPAGATION_NEVER) {
throw new IllegalTransactionStateException(
“Existing transaction found for transaction marked with propagation ‘never’”);
}
//以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。并把事务信息设置为null
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);
}
//新建事务,如果当前存在事务,把当前事务挂起。当然会创建新的连接,让业务在新的事务中完成,之后恢复挂起的事务。
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 {
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
//新开一个事务
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, suspendedResources);
doBegin(transaction, definition);
//初始化事务同步
prepareSynchronization(status, definition);
return status;
}
catch (RuntimeException | Error beginEx) {
resumeAfterBeginException(transaction, suspendedResources, beginEx);
throw beginEx;
}
}
//如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与PROPAGATION_REQUIRED类似的操作。
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()) {
// Create savepoint within existing Spring-managed transaction,
// through the SavepointManager API implemented by TransactionStatus.
// Usually uses JDBC 3.0 savepoints. Never activates Spring synchronization.
//如果是JDBC,使用保存点方式支持事务回滚
DefaultTransactionStatus status =
prepareTransactionStatus(definition, transaction, false, false, debugEnabled, null);
status.createAndHoldSavepoint();
return status;
}
else {
//如果是类似于JTA这种还无法使用保存点,处理方式如同PROPAGATION_REQUIRES_NEW
// Nested transaction through nested begin and commit/rollback calls.
// Usually only for JTA: Spring synchronization might get activated here
// in case of a pre-existing JTA transaction.
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
DefaultTransactionStatus status = newTransactionStatus(
definition, transaction, true, newSynchronization, debugEnabled, null);
doBegin(transaction, definition);
prepareSynchronization(status, definition);
return status;
}
}
// Assumably PROPAGATION_SUPPORTS or PROPAGATION_REQUIRED.
if (debugEnabled) {
logger.debug(“Participating in existing transaction”);
}
if (isValidateExistingTransaction()) {
if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
Integer currentIsolationLevel = TransactionSynchronizationManager.getCurrentTransactionIsolationLevel();
if (currentIsolationLevel == null || currentIsolationLevel != definition.getIsolationLevel()) {
Constants isoConstants = DefaultTransactionDefinition.constants;
throw new IllegalTransactionStateException(“Participating transaction with definition [” +
definition + "] specifies isolation level which is incompatible with existing transaction: " +
(currentIsolationLevel != null ?
isoConstants.toCode(currentIsolationLevel, DefaultTransactionDefinition.PREFIX_ISOLATION) :
“(unknown)”));
}
}
if (!definition.isReadOnly()) {
if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
throw new IllegalTransactionStateException(“Participating transaction with definition [” +
definition + “] is not marked as read-only but existing transaction is”);
}
}
}
boolean newSynchronization = (getTransactionSynchronization() != SYNCHRONIZATION_NEVER);
return prepareTransactionStatus(definition, transaction, false, newSynchronization, debugEnabled, null);
}
新开启事务:DataSourceTransactionManager#doBegin
/**
- This implementation sets the isolation level but ignores the timeout.
*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
//创建 DataSource 事务对象
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”);
}
//把链接设置给DataSourceTransactionObject
txObject.setConnectionHolder(new ConnectionHolder(newCon), true);
}
txObject.getConnectionHolder().setSynchronizedWithTransaction(true);
con = txObject.getConnectionHolder().getConnection();
//设置事务隔离级别 ,使用, 以及ReadOnly
Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
txObject.setPreviousIsolationLevel(previousIsolationLevel);
// Switch to manual commit if necessary. This is very expensive in some JDBC drivers,
// so we don’t want to do it unnecessarily (for example if we’ve explicitly
// configured the connection pool to set it already).
if (con.getAutoCommit()) {
txObject.setMustRestoreAutoCommit(true);
if (logger.isDebugEnabled()) {
logger.debug(“Switching JDBC Connection [” + con + “] to manual commit”);
}
//设置手动提交,由Spring来控制事务提交
con.setAutoCommit(false);
}
prepareTransactionalConnection(con, definition);
//设置事务Active为true
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);
}
}
这个方法是事务开始的方法,因为它已经尝试和数据库进行连接了,然后又做了一些基础设置
-
设置事务的隔离级别,如果DB的隔离级别和事务属性源(TransactionAttribute )即:用户定义的事务隔离级别不一致,使用用户定义的隔离级别
-
把事务自动提交改为false,由Spring来控制事务提交
-
把 TransactionActive 状态设置为true,代表事务是active 激活状态
-
设置事务超时时间
-
把连接绑定到当前对象
到这, createTransactionIfNecessary 方法中的业务就分析完了,接下来就是 调用 invocation.proceedWithInvocation()
去执行目标类的方法,如果出现异常,会走catch中的回滚事务代码。
回滚事务:completeTransactionAfterThrowing
代码回到TransactionAspectSupport#invokeWithinTransaction
,我们跟一下completeTransactionAfterThrowing(txInfo, ex);
回滚事务代码,源码如下
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);
}
//判断异常类型决定是否要回滚
//默认判断异常是否是 RuntimeException 类型或者是 Error 类型
//可以指定异常处理类型,例如:@Transactional(rollbackFor=Exception.class)
if (txInfo.transactionAttribute != null && txInfo.transactionAttribute.rollbackOn(ex)) {
try {
//走事务管理器的rollback回滚事务
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 {
// We don’t roll back on this exception.
// Will still roll back if TransactionStatus.isRollbackOnly() is true.
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;
}
}
}
}
首先是判断了异常的类型符不符合回滚条件,如果符合就调用事务管理器的回滚逻辑,如果不符合回滚条件就走事务管理器的commit提交事务,下面是回滚逻辑:AbstractPlatformTransactionManager#rollback
@Override
public final void rollback(TransactionStatus status) throws TransactionException {
if (status.isCompleted()) {
throw new IllegalTransactionStateException(
“Transaction is already completed - do not call commit or rollback more than once per transaction”);
}
//事务状态
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
//处理回滚
processRollback(defStatus, false);
}
/**
-
Process an actual rollback.
-
The completed flag has already been checked.
-
@param status object representing the transaction
-
@throws TransactionException in case of rollback failure
*/
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
try {
boolean unexpectedRollback = unexpected;
try {
//触发事务同步器TransactionSynchronization中的beforeCompletion回调
//比如调用SqlSessionSynchronization#beforeCompletion 释放资源,sqlSession close等
triggerBeforeCompletion(status);
//如果有保存点,回滚到保存点
本次面试答案,以及收集到的大厂必问面试题分享:
transaction");
}
//事务状态
DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
//处理回滚
processRollback(defStatus, false);
}
/**
-
Process an actual rollback.
-
The completed flag has already been checked.
-
@param status object representing the transaction
-
@throws TransactionException in case of rollback failure
*/
private void processRollback(DefaultTransactionStatus status, boolean unexpected) {
try {
boolean unexpectedRollback = unexpected;
try {
//触发事务同步器TransactionSynchronization中的beforeCompletion回调
//比如调用SqlSessionSynchronization#beforeCompletion 释放资源,sqlSession close等
triggerBeforeCompletion(status);
//如果有保存点,回滚到保存点
本次面试答案,以及收集到的大厂必问面试题分享:
[外链图片转存中…(img-xURDayUm-1715327210243)]