


How to use JTA components to implement multi-data source transaction management in SpringBoot2
1. Introduction to JTA components
1. Basic concepts of JTA
JTA is Java-Transaction-API. JTA allows applications to perform distributed transaction processing, that is, between two or more Access and update data on network computer resources. The JDBC driver's support for JTA greatly enhances data access capabilities.
The XA protocol is a set of distributed transaction management specifications at the database level. JTA is the implementation of the XA protocol in Java. Multiple databases or message vendors implement the JTA interface. Developers only need to call the SpringJTA interface. Can realize JTA transaction management function.
JTA transactions are more powerful than JDBC transactions. A JTA transaction can have multiple participants, while a JDBC transaction is limited to a single database connection. Any of the following Java platform components can participate in a JTA transaction
2. Distributed transaction
Distributed transaction (DistributedTransaction) includes a transaction manager (TransactionManager) and one or more Resource Manager that supports XA protocol.
The resource manager is any type of persistent data storage container, such as relational databases commonly used in development: MySQL, Oracle, etc., and message middleware RocketMQ, RabbitMQ, etc.
The transaction manager provides transaction declaration, transaction resource management, synchronization, transaction context propagation and other functions, and is responsible for the mutual communication of all transaction participants in the unit. The JTA specification defines the interface for the transaction manager to interact with other transaction participants, and other transaction participants to interact with the transaction manager.
2. SpringBoot integrates JTA
Overall structure diagram of the project
<!--SpringBoot核心依赖-->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-web</artifactid>
</dependency>
<!--JTA组件核心依赖-->
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-jta-atomikos</artifactid>
</dependency>
2. Environment ConfigurationThe configuration of jtaManager here is very critical in the log output.
spring: jta: transaction-manager-id: jtaManager # 数据源配置 datasource: type: com.alibaba.druid.pool.DruidDataSource data01: driverClassName: com.mysql.jdbc.Driver dbUrl: jdbc:mysql://localhost:3306/data-one username: root password: 000000 data02: driverClassName: com.mysql.jdbc.Driver dbUrl: jdbc:mysql://localhost:3306/data-two username: root password: 0000003. Core containerThe configuration methods for the two database connections here are the same, and you can download and read them in the source code. The basic idea is to hand over the data source to the JTA component for unified management to facilitate transaction communication.
Data source parameters
@Component @ConfigurationProperties(prefix = "spring.datasource.data01") public class DruidOneParam { private String dbUrl; private String username; private String password; private String driverClassName; }
JTA component configuration
package com.jta.source.conifg; @Configuration @MapperScan(basePackages = {"com.jta.source.mapper.one"},sqlSessionTemplateRef = "data01SqlSessionTemplate") public class DruidOneConfig { private static final Logger LOGGER = LoggerFactory.getLogger(DruidOneConfig.class) ; @Resource private DruidOneParam druidOneParam ; @Primary @Bean("dataSourceOne") public DataSource dataSourceOne () { // 设置数据库连接 MysqlXADataSource mysqlXADataSource = new MysqlXADataSource(); mysqlXADataSource.setUrl(druidOneParam.getDbUrl()); mysqlXADataSource.setUser(druidOneParam.getUsername()); mysqlXADataSource.setPassword(druidOneParam.getPassword()); mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true); // 事务管理器 AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean(); atomikosDataSourceBean.setXaDataSource(mysqlXADataSource); atomikosDataSourceBean.setUniqueResourceName("dataSourceOne"); return atomikosDataSourceBean; } @Primary @Bean(name = "sqlSessionFactoryOne") public SqlSessionFactory sqlSessionFactoryOne( @Qualifier("dataSourceOne") DataSource dataSourceOne) throws Exception{ // 配置Session工厂 SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSourceOne); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sessionFactory.setMapperLocations(resolver.getResources("classpath*:/dataOneMapper/*.xml")); return sessionFactory.getObject(); } @Primary @Bean(name = "data01SqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate( @Qualifier("sqlSessionFactoryOne") SqlSessionFactory sqlSessionFactory) { // 配置Session模板 return new SqlSessionTemplate(sqlSessionFactory); } }4. Test comparisonPassed here Comparing the test results of the two methods, when performing data operations between the two data sources, you only need to add the @Transactional annotation to the interface method, so as to ensure that the data is consistent between the two data sources.
@Service public class TransferServiceImpl implements TransferService { @Resource private UserAccount01Mapper userAccount01Mapper ; @Resource private UserAccount02Mapper userAccount02Mapper ; @Override public void transfer01() { userAccount01Mapper.transfer("jack",100); System.out.println("i="+1/0); userAccount02Mapper.transfer("tom",100); } @Transactional @Override public void transfer02() { userAccount01Mapper.transfer("jack",200); System.out.println("i="+1/0); userAccount02Mapper.transfer("tom",200); } }
The above is the detailed content of How to use JTA components to implement multi-data source transaction management in SpringBoot2. For more information, please follow other related articles on the PHP Chinese website!

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.