您的位置:首頁技術文章
文章詳情頁

spring是如何實現聲明式事務的

瀏覽:26日期:2023-07-17 14:21:37
前言

今天我們來講講spring的聲明式事務。

開始

說到聲明式事務,我們現在回顧一下事務這個概念,什么是事務呢,事務指的是邏輯上的⼀組操作,組成這組操作的各個單元,要么全部成功,要么全部不成功。從而確保了數據的準確與安全。事務有著四大特性(ACID),分別是原子性(Atomicity)原⼦性是指事務是⼀個不可分割的⼯作單位,事務中的操作要么都發⽣,要么都不發⽣。

⼀致性(Consistency)事務必須使數據庫從⼀個⼀致性狀態變換到另外⼀個⼀致性狀態。

隔離性(Isolation)事務的隔離性是多個⽤戶并發訪問數據庫時,數據庫為每⼀個⽤戶開啟的事務,每個事務不能被其他事務的操作數據所⼲擾,多個并發事務之間要相互隔離。

持久性(Durability) 持久性是指⼀個事務⼀旦被提交,它對數據庫中數據的改變就是永久性的,接下來即使數據庫發⽣故障

也不應該對其有任何影響。

在spring中,一共有兩種方式可以實現事務控制,分別是編程式事務和聲明式事務。編程式事務指的是在代碼中添加事務控制代碼,而聲明式事務指的是利用xml或者注解的形式來配置控制事務,下面就以純注解配置聲明式事務為例進行剖析。

spring開啟聲明式事務的注解是@EnableTransactionManagement,講到這里首先要明白一點,spring的事務管理器管理事務其實就是利用aop的方式,通過創建動態代理加上攔截,實現的事務管理。在spring的配置類中加上這個注解,就支持了聲明式事務,那么spring是怎么通過這么一個注解就可以支持事務的呢,我們來看代碼。首先我們看到,在這個注解上,import了一個selector

@Import(TransactionManagementConfigurationSelector.class)

我們看這個selector類中的這么一段代碼

@Override protected String[] selectImports(AdviceMode adviceMode) { switch (adviceMode) { case PROXY: return new String[] {AutoProxyRegistrar.class.getName(), ProxyTransactionManagementConfiguration.class.getName()}; case ASPECTJ: return new String[] {determineTransactionAspectClass()}; default: return null; } }

這段代碼中,引入了AutoProxyRegistrar和ProxyTransactionManagementConfiguration這兩個類,我們先來看AutoProxyRegistrar這個類,這個類中有一段這樣的代碼

if (mode == AdviceMode.PROXY) { //重要的是這句代碼 AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry); if ((Boolean) proxyTargetClass) { AopConfigUtils.forceAutoProxyCreatorToUseClassProxying(registry); return; }}//我們進到這個方法中@Nullable public static BeanDefinition registerAutoProxyCreatorIfNecessary( BeanDefinitionRegistry registry, @Nullable Object source) {//可以看到引入了InfrastructureAdvisorAutoProxyCreator這個類,那么這個類又是什么呢 return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source); }//先看一下public class InfrastructureAdvisorAutoProxyCreator extends AbstractAdvisorAutoProxyCreator { @Nullable private ConfigurableListableBeanFactory beanFactory; @Override protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) { super.initBeanFactory(beanFactory); this.beanFactory = beanFactory; } @Override protected boolean isEligibleAdvisorBean(String beanName) { return (this.beanFactory != null && this.beanFactory.containsBeanDefinition(beanName) && this.beanFactory.getBeanDefinition(beanName).getRole() == BeanDefinition.ROLE_INFRASTRUCTURE); }}

看一下繼承結構圖

spring是如何實現聲明式事務的

可以看到這個方法間接繼承于SmartInstantiationAwareBeanPostProcessor,最終繼承于BeanPostProcessor,這說明InfrastructureAdvisorAutoProxyCreator類是一個后置處理器,并且跟 spring AOP 開啟@EnableAspectJAutoProxy 時注冊的AnnotationAwareAspectJProxyCreator實現的是同⼀個接口,這也對應了我之前所說聲明式事務是springAOP思想的一種應用。

然后我們回過頭來再看ProxyTransactionManagementConfiguration這個類,我們看到其中有一個事務增強器,一個屬性解析器和是一個事務攔截器

@Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor( TransactionAttributeSource transactionAttributeSource, TransactionInterceptor transactionInterceptor) { // 事務增強器 BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor(); // 注入屬性解析器 advisor.setTransactionAttributeSource(transactionAttributeSource); // 注入事務攔截器 advisor.setAdvice(transactionInterceptor); if (this.enableTx != null) { advisor.setOrder(this.enableTx.<Integer>getNumber('order')); } return advisor; } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) // 屬性解析器 public TransactionAttributeSource transactionAttributeSource() { return new AnnotationTransactionAttributeSource(); } @Bean @Role(BeanDefinition.ROLE_INFRASTRUCTURE) // 事務攔截器 public TransactionInterceptor transactionInterceptor(TransactionAttributeSource transactionAttributeSource) { TransactionInterceptor interceptor = new TransactionInterceptor(); interceptor.setTransactionAttributeSource(transactionAttributeSource); if (this.txManager != null) { interceptor.setTransactionManager(this.txManager); } return interceptor; }

先看看屬性解析器

//注解解析器集合 private final Set<TransactionAnnotationParser> annotationParsers;

這是一個注解解析器的集合,可以添加多種注解解析器,在這里我們主要關注的是spring事務注解解析器SpringTransactionParser,看一下相關代碼

protected TransactionAttribute parseTransactionAnnotation(AnnotationAttributes attributes) { RuleBasedTransactionAttribute rbta = new RuleBasedTransactionAttribute(); // 對應Transaction注解的相關屬性 Propagation propagation = attributes.getEnum('propagation'); rbta.setPropagationBehavior(propagation.value()); Isolation isolation = attributes.getEnum('isolation'); rbta.setIsolationLevel(isolation.value()); rbta.setTimeout(attributes.getNumber('timeout').intValue()); rbta.setReadOnly(attributes.getBoolean('readOnly')); rbta.setQualifier(attributes.getString('value')); List<RollbackRuleAttribute> rollbackRules = new ArrayList<>(); for (Class<?> rbRule : attributes.getClassArray('rollbackFor')) { rollbackRules.add(new RollbackRuleAttribute(rbRule)); } for (String rbRule : attributes.getStringArray('rollbackForClassName')) { rollbackRules.add(new RollbackRuleAttribute(rbRule)); } for (Class<?> rbRule : attributes.getClassArray('noRollbackFor')) { rollbackRules.add(new NoRollbackRuleAttribute(rbRule)); } for (String rbRule : attributes.getStringArray('noRollbackForClassName')) { rollbackRules.add(new NoRollbackRuleAttribute(rbRule)); } rbta.setRollbackRules(rollbackRules); return rbta; }

可以看到這段代碼中的Enum和ClassArray其實正是@Transaction注解中的相關屬性,這個屬性解析器的作用之一就是用來解析@Transaction注解中的屬性看完了屬性解析器,我們接下來看事務攔截器TransactionInterceptor,其中重要的是這段代碼

@Override @Nullable public Object invoke(MethodInvocation invocation) throws Throwable { // Work out the target class: may be {@code null}. // The TransactionAttributeSource should be passed the target class // as well as the method, which may be from an interface. Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null); // Adapt to TransactionAspectSupport’s invokeWithinTransaction... // 增加事務支持 return invokeWithinTransaction(invocation.getMethod(), targetClass, invocation::proceed); }

然后我們進到這個方法里面

@Nullable protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass, final InvocationCallback invocation) throws Throwable { // If the transaction attribute is null, the method is non-transactional. // 獲取屬性解析器,在配置類ProxyTransactionManagementConfiguration配置時加入 TransactionAttributeSource tas = getTransactionAttributeSource(); final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null); final TransactionManager tm = determineTransactionManager(txAttr); if (this.reactiveAdapterRegistry != null && tm instanceof ReactiveTransactionManager) { ReactiveTransactionSupport txSupport = this.transactionSupportCache.computeIfAbsent(method, key -> { if (KotlinDetector.isKotlinType(method.getDeclaringClass()) && KotlinDelegate.isSuspend(method)) { throw new TransactionUsageException( 'Unsupported annotated transaction on suspending function detected: ' + method + '. Use TransactionalOperator.transactional extensions instead.'); } ReactiveAdapter adapter = this.reactiveAdapterRegistry.getAdapter(method.getReturnType()); if (adapter == null) { throw new IllegalStateException('Cannot apply reactive transaction to non-reactive return type: ' + method.getReturnType()); } return new ReactiveTransactionSupport(adapter); }); return txSupport.invokeWithinTransaction( method, targetClass, invocation, txAttr, (ReactiveTransactionManager) tm); } // 獲取事務管理器 PlatformTransactionManager ptm = asPlatformTransactionManager(tm); final String joinpointIdentification = methodIdentification(method, targetClass, txAttr); if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) { // Standard transaction demarcation with getTransaction and commit/rollback calls. TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification); Object retVal; try { // This is an around advice: Invoke the next interceptor in the chain. // This will normally result in a target object being invoked. retVal = invocation.proceedWithInvocation(); } catch (Throwable ex) { // target invocation exception // 目標方法拋異常,會執行回滾的操作 completeTransactionAfterThrowing(txInfo, ex); throw ex; } finally { cleanupTransactionInfo(txInfo); } if (vavrPresent && VavrDelegate.isVavrTry(retVal)) { // Set rollback-only in case of Vavr failure matching our rollback rules... TransactionStatus status = txInfo.getTransactionStatus(); if (status != null && txAttr != null) { retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status); } } // 目標方法正常運行,會執行commitTransactionAfterReturning,執行事務提交操作 commitTransactionAfterReturning(txInfo); return retVal; } else { final ThrowableHolder throwableHolder = new ThrowableHolder(); // It’s a CallbackPreferringPlatformTransactionManager: pass a TransactionCallback in. try { Object result = ((CallbackPreferringPlatformTransactionManager) ptm).execute(txAttr, status -> { TransactionInfo txInfo = prepareTransactionInfo(ptm, txAttr, joinpointIdentification, status); try { Object retVal = invocation.proceedWithInvocation(); if (vavrPresent && VavrDelegate.isVavrTry(retVal)) { // Set rollback-only in case of Vavr failure matching our rollback rules... retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status); } return retVal; } 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; } } }總結

總體來說,spring實現聲明式事務的過程是這樣的

@EnableTransactionManagement 注解,通過@import引⼊了TransactionManagementConfigurationSelector類,它的selectImports⽅法導⼊了另外兩個類:AutoProxyRegistrar和ProxyTransactionManagementConfiguration AutoProxyRegistrar類中方法registerBeanDefinitions中,通過 AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry)引⼊InfrastructureAdvisorAutoProxyCreator,是一個后置處理器類 ProxyTransactionManagementConfiguration 是⼀個添加了@Configuration注解的配置類,注冊了事務增強器(注⼊屬性解析器、事務攔截器)AnnotationTransactionAttributeSource和TransactionInterceptor,AnnotationTransactionAttributeSource內部持有了⼀個解析器集合 Set annotationParsers,具體使⽤的是SpringTransactionAnnotationParser解析器,用來解析@Transactional的事務屬性,事務攔截器TransactionInterceptor實現了MethodInterceptor接⼝,該通用攔截會在產⽣代理對象之前和aop增強合并,最終⼀起影響到代理對象,TransactionInterceptor的invoke⽅法中invokeWithinTransaction會觸發原有業務邏輯調用(增強事務)

到此這篇關于spring是如何實現聲明式事務的的文章就介紹到這了,更多相關spring 聲明式事務內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
国产综合久久一区二区三区