首頁 > 軟體

Spring Transaction事務實現流程原始碼解析

2022-09-14 22:07:13

一、基於xml形式開啟Transaction

1. 建立資料庫user

/*
 Navicat Premium Data Transfer
 Source Server         : win-local
 Source Server Type    : MySQL
 Source Server Version : 50737
 Source Host           : localhost:3306
 Source Schema         : db0
 Target Server Type    : MySQL
 Target Server Version : 50737
 File Encoding         : 65001
 Date: 24/04/2022 20:27:41
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;

2. 建立一個maven 專案

不用Springboot依賴,引入mysql驅動依賴、spring-beans、spring-jdbc、Spring-context依賴

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.3.18</version>
        </dependency>
        <!-- spring jdbc 依賴spring-tx -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.18</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
        </dependency>
    </dependencies>

3. 通過xml形式設定事務

1) 建立Spring名稱空間

首先在resources目錄下建立一個spring.xml檔案,Spring框架為了宣告自己的Xml規範,在<beans>標籤裡定義了spring 框架指定模組的協定設定, 我們可以通過Index of /schema存取spring框架的所有模組包,各模組包含了不同版本的xsd檔案。

點選進入context目錄,檢視xsd檔案:

比如我要通過xml的形式設定一個bean, 需要在beans標籤中宣告 xmln的值為:

http://www.springframework.org/schema/beans

如果我想用spring的context模組,那麼需要宣告

xmlns:context="http://www.springframework.org/schema/context"

同時在xsi: schemeLocation裡新增context的url和spring-contxt.xsd的url:

http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd

例如我建立一個能在xml中使用spring-beans模組,spring-txt模組,spring-context模組的設定如下:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd
">
</beans>

如果沒有在beans標籤裡宣告協定,那麼在設定bean時會出現找不到指定標籤的問題。

2) 開啟事務設定

在spring.xml檔案中新增設定事務設定,使用 annotation-driven 屬性開啟事務啟動,

    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" mode="proxy"/>

proxy-target-class預設為false, mode預設模式為proxy,可不用設定,待會從原始碼角度分析不同模式的事務開啟。

接著設定transactionManager, 指定class="org.springframework.jdbc.datasource.DataSourceTransactionManager"

    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" mode="proxy"/>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="ds"/>
    </bean>

DataSourceTransactionManager裡包含了DataSource屬性設定:

因此我們需要接著設定資料來源bean 別名為

    <bean id="ds" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db0?useSSL=false"/>
        <property name="initialSize" value="5"/>
        <property name="maxIdle" value="2"/>
        <property name="maxTotal" value="100"/>
    </bean>

接著給Service設定一個bean, 參照dataSource資料來源。

    <!-- 設定bean,指定資料來源-->
    <bean id="userService" class="service.UserService">
        <property name="dataSource" ref="ds"/>
    </bean>

3) 建立UserService類

通過dataSouce bean注入JDBCTemplate, 新增一個update(int id,String name)方法, 類上新增@Transactional(propagation = Propagation.REQUIRED)。

package service;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.sql.DataSource;
@Transactional(propagation = Propagation.REQUIRED)
public class UserService {
    private JdbcTemplate jdbcTemplate;
    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
    public String getUserName(int id) {
        return jdbcTemplate.query("select * from db0.user where id= ?", rs -> rs.next() ? rs.getString(2) : "", new Object[]{id});
    }
    public void updateUser(int id, String name) {
        jdbcTemplate.update(" update  user set name =? where id= ?", new Object[]{name, id});
//        throw new RuntimeException("error!");
    }
}

4. 測試事務

使用ClassPathXmlApplicationContext類載入spring.xml檔案

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;
public class UserServiceTests {
    @Test
    public void testTransaction() {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        UserService userService = context.getBean("userService", UserService.class);
        String name = userService.getUserName(1);
        System.out.println("名字:"+name);
        userService.updateUser(1, "bing");
        String updateName = userService.getUserName(1);
        System.out.println("更新後的名字:" + updateName);
    }
}

資料庫一條記錄:

1) 丟擲RuntimeException

update方法裡放開//throw new RuntimeException("error!"); 註釋,執行後

資料庫裡的記錄沒有修改,@Tranasctional註解生效。

2) 註釋掉RuntimeException

重新執行後,觀察結果

資料庫也更新過來了。

前面的篇幅從xml的設定形式解釋了Transaction整合過程,為什麼要從xml形式入手transaction, 是為了後面閱讀Spring-tx原始碼做準備。

二、事務開啟入口TxNamespaceHandler

根據spring.xml檔案裡設定的tx:annitation-driven 關鍵字在Spring框架裡全域性搜尋,找到目標類TxNamespaceHandler。位於spring-tx模組中的 org.springframework.transaction.config包下。

/*
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.transaction.config;
import org.w3c.dom.Element;
import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
/**
 * {@code NamespaceHandler} allowing for the configuration of
 * declarative transaction management using either XML or using annotations.
 *
 * <p>This namespace handler is the central piece of functionality in the
 * Spring transaction management facilities and offers two approaches
 * to declaratively manage transactions.
 *
 * <p>One approach uses transaction semantics defined in XML using the
 * {@code <tx:advice>} elements, the other uses annotations
 * in combination with the {@code <tx:annotation-driven>} element.
 * Both approached are detailed to great extent in the Spring reference manual.
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @since 2.0
 */
public class TxNamespaceHandler extends NamespaceHandlerSupport {
	static final String TRANSACTION_MANAGER_ATTRIBUTE = "transaction-manager";
	static final String DEFAULT_TRANSACTION_MANAGER_BEAN_NAME = "transactionManager";
	static String getTransactionManagerName(Element element) {
		return (element.hasAttribute(TRANSACTION_MANAGER_ATTRIBUTE) ?
				element.getAttribute(TRANSACTION_MANAGER_ATTRIBUTE) : DEFAULT_TRANSACTION_MANAGER_BEAN_NAME);
	}
	@Override
	public void init() {
		registerBeanDefinitionParser("advice", new TxAdviceBeanDefinitionParser());
		// 註冊事務
		registerBeanDefinitionParser("annotation-driven", new AnnotationDrivenBeanDefinitionParser());
		registerBeanDefinitionParser("jta-transaction-manager", new JtaTransactionManagerBeanDefinitionParser());
	}
}

找到了annotation-driven, 這個地方建立了一個AnnotationDrivenBeanDefinitionParser範例。

AnnotationDrivenBeanDefinitionParser

AnnotationDrivenBeanDefinitionParser 類的作用是解析spring.xml裡的設定<tx:annotation-driven>標籤,並根據設定的mode選擇不同的模式取建立Transaction的整個初始化流程,此處也就是整個架Transaction架構的開始地方。

Spring事務註冊的模式為動態代理模式,具體實現有2種: aspectj和proxy,可通過設定來選擇使用那種形式的事務註冊, 如果不設定mode那麼使用預設的proxy形式建立,如果我們要使用aspectj模式開啟事務,那麼就設定mode="aspectj"。

<tx:annotation-driven transaction-manager="transactionManager" mode="aspectj">

我們可以看到Spring事務的開啟是預設是以AOP為基礎的。

三、AOP驅動事務

AopAutoProxyConfigurer 的configureAutoProxyCreator方法註冊了3個Bean, 該3個Bean 是驅動Spring 事務架構的核心支柱,分別是TransactionAttributeSource、TransactionInterceptor、TransactionAttributeSourceAdvisor。

	private static class AopAutoProxyConfigurer {
		public static void configureAutoProxyCreator(Element element, ParserContext parserContext) {
			AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(parserContext, element);
			String txAdvisorBeanName = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME;
			if (!parserContext.getRegistry().containsBeanDefinition(txAdvisorBeanName)) {
				Object eleSource = parserContext.extractSource(element);
				// Create the TransactionAttributeSource definition.
				RootBeanDefinition sourceDef = new RootBeanDefinition(
						"org.springframework.transaction.annotation.AnnotationTransactionAttributeSource");
				sourceDef.setSource(eleSource);
				sourceDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
				String sourceName = parserContext.getReaderContext().registerWithGeneratedName(sourceDef);
				// Create the TransactionInterceptor definition.
				RootBeanDefinition interceptorDef = new RootBeanDefinition(TransactionInterceptor.class);
				interceptorDef.setSource(eleSource);
				interceptorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
				registerTransactionManager(element, interceptorDef);
				interceptorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
				String interceptorName = parserContext.getReaderContext().registerWithGeneratedName(interceptorDef);
				// Create the TransactionAttributeSourceAdvisor definition.
				RootBeanDefinition advisorDef = new RootBeanDefinition(BeanFactoryTransactionAttributeSourceAdvisor.class);
				advisorDef.setSource(eleSource);
				advisorDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
				advisorDef.getPropertyValues().add("transactionAttributeSource", new RuntimeBeanReference(sourceName));
				advisorDef.getPropertyValues().add("adviceBeanName", interceptorName);
				if (element.hasAttribute("order")) {
					advisorDef.getPropertyValues().add("order", element.getAttribute("order"));
				}
				// 事務通知器 transaction advisor, 基於AOP實現的advisor
				parserContext.getRegistry().registerBeanDefinition(txAdvisorBeanName, advisorDef);
				CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource);
				compositeDef.addNestedComponent(new BeanComponentDefinition(sourceDef, sourceName));
				compositeDef.addNestedComponent(new BeanComponentDefinition(interceptorDef, interceptorName));
				compositeDef.addNestedComponent(new BeanComponentDefinition(advisorDef, txAdvisorBeanName));
				parserContext.registerComponent(compositeDef);
			}
		}
	}

其中TransactionInterceptor是Spring事務的目標方法的增強,通過代理完成Spring 事務的提交、例外處理和回滾。

TransactionInterceptor

TransactionInterceptor是Spring 事務對目標方法的增強器,說簡單點就是一層代理,基於Aop實現,實現了spring-aop的Advice介面,同時實現了IntializingBean和BeanFactoryAware介面,只要有事務的執行,那麼目標方法的呼叫類在invoke()方法會生成一個代理物件,通過invoke()方法對目標呼叫方法進行增強。

@FunctionalInterface
public interface MethodInterceptor extends Interceptor {
	/**
	 * Implement this method to perform extra treatments before and
	 * after the invocation. Polite implementations would certainly
	 * like to invoke {@link Joinpoint#proceed()}.
	 * @param invocation the method invocation joinpoint
	 * @return the result of the call to {@link Joinpoint#proceed()};
	 * might be intercepted by the interceptor
	 * @throws Throwable if the interceptors or the target object
	 * throws an exception
	 */
	Object invoke(MethodInvocation invocation) throws Throwable;
}

TransactionInterceptor的invoke()實現:

	@Override
	@Nullable
	public Object invoke(final 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);
	}

建立事務

Spring 建立事務的方式有二種: 宣告式事務和程式設計式事務, 我們可以通過分析一種理解核心流程和原理即可。

進入invokeWithinTransaction()方法直接看宣告式事務執行過程的原始碼:

	if (txAttr == null || !(tm instanceof CallbackPreferringPlatformTransactionManager)) {
			// Standard transaction demarcation with getTransaction and commit/rollback calls.
			// 建立事務
			TransactionInfo txInfo = createTransactionIfNecessary(tm, txAttr, joinpointIdentification);
			Object retVal = null;
			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);
			}
			// 提交事務
			commitTransactionAfterReturning(txInfo);
			return retVal;
		}

invokeWithinTransaction方法做了哪些事?

1)通過createTransactionIfNecessary方法建立一個事務,相當於此處開啟一個事務。

2)invocation.proceedWithInvocation() 執行目標方法呼叫。

3) 如果出現異常,那麼completeTransactionAfterThrowing處理異常。

4) 在finally 清除掉transaction相關的資訊,同時在commitTransactionAfterReturning 提交事務。

回滾事務

我們可以從上面的原始碼中發現通過transactionManager執行回滾操作。

txInfo.getTransactionManager().rollback(txInfo.getTransactionStatus());

到此這篇關於Spring Transaction事務實現流程原始碼解析的文章就介紹到這了,更多相關Spring Transaction內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com