diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 88d4a12..515823f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -88,6 +88,8 @@ jobs: # tx-seata-sample 依赖的 Seata 在 AOT 处理阶段就会构造 GlobalTransactionScanner # 并要求 Seata Server 可达,且其应用上下文在 AOT 类型预判定阶段存在 null Advisor # 问题,故暂不纳入。 + # tx-atomikos-sample 依赖的 Atomikos JTA/XA 在 native image 下还需要额外的 + # reachability metadata,待专项处理后纳入。 - name: Native test with Maven run: | ./mvnw -B -e -PnativeTest clean test -pl "${{ matrix.module }}" diff --git a/.gitignore b/.gitignore index 1ca1599..b1fb853 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,10 @@ */target/ target +### Atomikos transaction logs (tx-atomikos-sample) ### +tmlog*.log +transaction-logs/ + ### STS ### .apt_generated .classpath diff --git a/README.md b/README.md index 1309a43..d9b6186 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,9 @@ - tx-local-sample:本地事务示例项目★★★★★★必看★★★★★★ - tx-seata-sample:基于seata的分布式事务集成使用示例,Seata Server 与数据库的准备、关键配置和本地运行步骤见 [模块 README](./spring-boot-4/tx-seata-sample/README.md) +- tx-atomikos-sample:基于 Atomikos XA 的分布式事务集成使用示例,Boot 4 下 JTA 事务管理器的手工装配、 + `@Transactional` 与多数据源 MyBatis 的冲突、XA 建表注意点见 + [模块 README](./spring-boot-4/tx-atomikos-sample/README.md) ## Spring Boot 3(`spring-boot-3/`) diff --git a/spring-boot-4/pom.xml b/spring-boot-4/pom.xml index 73311ac..3a98fc1 100644 --- a/spring-boot-4/pom.xml +++ b/spring-boot-4/pom.xml @@ -29,6 +29,9 @@ 2.8.0 3.40.0-RELEASE 2.6.0 + + 6.0.1 @@ -45,6 +48,7 @@ quartz-sample shardingsphere-jdbc-5.x-core-sample spel-sample + tx-atomikos-sample tx-local-sample tx-seata-sample @@ -133,6 +137,19 @@ seata-spring-boot-starter ${seata-spring-boot-starter.version} + + + com.atomikos + transactions-jdbc + ${atomikos.version} + jakarta + + + com.atomikos + transactions-jta + ${atomikos.version} + jakarta + diff --git a/spring-boot-4/tx-atomikos-sample/README.md b/spring-boot-4/tx-atomikos-sample/README.md new file mode 100644 index 0000000..904e1a5 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/README.md @@ -0,0 +1,152 @@ +# tx-atomikos-sample + +基于 `dynamic-datasource-spring-boot4-starter` + MyBatis + Atomikos XA 的跨数据源分布式事务示例。 +示例把订单(order)与账户(account)拆到两个数据源中,下单流程在一个 JTA 事务里跨库写入, +任意一步失败时由 Atomikos 以两阶段提交(2PC)保证两个库一起回滚。 + +本模块暂不支持 GraalVM native image:Atomikos 的 JTA/XA 在 native image 下还需要额外的 +reachability metadata,因此未纳入 Native Test CI,与 tx-seata-sample 同属先例, +详见 [GraalVM Native Image](../../docs/graalvm-native-image.md)。 + +## 技术栈 + +| 组件 | 版本 | +| --- | --- | +| Spring Boot | 4.1.1 | +| dynamic-datasource-spring-boot4-starter | 4.7.0(取自根 `pom.xml` 的 `ds.version`) | +| Atomikos(`transactions-jdbc` / `transactions-jta`) | 6.0.1 `jakarta` classifier,版本取自父模块 `spring-boot-4-samples` 的 `atomikos.version` | +| H2 | 由 Spring Boot BOM 管理,XA 数据源为 `org.h2.jdbcx.JdbcDataSource` | + +## 业务流程 + +入口是 `OrderService#placeOrder`: + +1. `@DS("order")` 切到订单数据源,`UserTransaction.begin()` 开启 JTA 事务,插入 `orders`; +2. `AccountService#deduct` 以 `@DS("account")` 切到账户数据源,余额不足时影响行数为 0, + 抛出 `InsufficientBalanceException`; +3. `UserTransaction.commit()` 提交,Atomikos 对 order、account 两个 XA 资源做两阶段提交; + 任一步抛异常则 `rollback()`,两个库一起回滚。 + +## 关键配置 + +```yaml +spring: + datasource: + dynamic: + primary: order + atomikos: # 全局连接池参数,可在单个数据源下用同样的 key 覆盖 + min-pool-size: 1 + max-pool-size: 10 + borrow-connection-timeout: 30 + max-idle-time: 60 + maintenance-interval: 60 + datasource: + order: + # type 必须显式声明:Hikari 创建器优先级更高,type 缺省会接管并把 XA 数据源类 + # 误当作 java.sql.Driver 加载而启动失败。 + type: com.atomikos.jdbc.AtomikosDataSourceBean + # driver-class-name 指向 XA 数据源类(不是普通 JDBC Driver) + driver-class-name: org.h2.jdbcx.JdbcDataSource + url: jdbc:h2:mem:order;DB_CLOSE_DELAY=-1 + username: sa + password: "" + account: + type: com.atomikos.jdbc.AtomikosDataSourceBean + driver-class-name: org.h2.jdbcx.JdbcDataSource + url: jdbc:h2:mem:account;DB_CLOSE_DELAY=-1 + username: sa + password: "" +``` + +换成生产数据库时只需替换 `driver-class-name` 与连接信息:MySQL 用 +`com.mysql.cj.jdbc.MysqlXADataSource`,PostgreSQL 用 `org.postgresql.xa.PGXADataSource`。 + +内置支持的 XA 数据源类(`XADataSourceEnum`): + +| 数据库 | XA 数据源类 | +| --- | --- | +| MySQL 8+ | `com.mysql.cj.jdbc.MysqlXADataSource` | +| MySQL 5.1 | `com.mysql.jdbc.jdbc2.optional.MysqlXADataSource` | +| Oracle | `oracle.jdbc.xa.client.OracleXADataSource` | +| PostgreSQL | `org.postgresql.xa.PGXADataSource` | +| H2 | `org.h2.jdbcx.JdbcDataSource` | + +其他数据库的 XA 数据源类不在枚举内,不会被 Atomikos 创建器认领,需要自定义 `DataSourceCreator`。 + +Atomikos 连接池参数(`spring.datasource.dynamic.atomikos.*`,单数据源下可用同名 key 覆盖): + +| 参数 | 默认值 | 说明 | +| --- | --- | --- | +| `min-pool-size` | 1 | 最小连接数 | +| `max-pool-size` | 10 | 最大连接数 | +| `borrow-connection-timeout` | 30 | 池空时等待连接的秒数 | +| `reap-timeout` | 0 | 连接最大借用秒数;**Atomikos 6 已移除该配置**,4/5 生效 | +| `max-idle-time` | 60 | 超出 min-pool-size 的空闲连接保留秒数 | +| `test-query` | `SELECT 1` | 归还连接前的验证语句 | +| `maintenance-interval` | 60 | 池维护线程间隔秒数 | +| `default-isolation-level` | -1 | 默认隔离级别,负值忽略 | +| `max-lifetime` | 60 | 连接最大存活秒数,0 为不限制 | + +## 四个必须手工处理的点 + +1. **Boot 4 不再自动装配 Atomikos 的 JTA 事务管理器**(Boot 3 及以前会自动装配), + 需要自行声明 `UserTransactionManager` 与 `JtaTransactionManager`,见 + `config/JtaConfig`;同时 Atomikos 的 `transactions-jta` 把 `jakarta.transaction-api` + 声明为 provided,不会随依赖传递,需要显式引入,否则事务管理器会回退成 + `JdbcTransactionManager`,XA 根本不会发生。 +2. **多数据源 + MyBatis 不要用 Spring 的 `@Transactional`**:MyBatis-Spring 在 Spring 事务 + 同步激活时会把整个事务复用同一个 SqlSession(连同同一个连接),连接按事务内第一条语句的 + `@DS` 确定数据源,后续 `@DS` 切换全部失效(表现为第二个库 "Table not found")。 + 本示例用编程式 JTA: + + ```java + @DS("order") + public void placeOrder(PlaceOrderRequest request) { + try { + userTransactionManager.begin(); + orderMapper.insert(order); // -> order 数据源 + accountService.deduct(request.getUserId(), amount); // @DS("account") -> account 数据源 + userTransactionManager.commit(); // 两个 XA 资源 2PC + } catch (RuntimeException e) { + userTransactionManager.rollback(); // 两个库一起回滚 + throw e; + } catch (Exception e) { + userTransactionManager.rollback(); + throw new IllegalStateException("JTA 事务提交失败", e); + } + } + ``` + + 完整说明见 `service/OrderService` 的类注释。 +3. **MyBatis 侧使用 `AtomikosTransactionFactory`**(`config/MyBatisConfig`):它在每次 MyBatis + 事务开始时先按当前 `@DS` 确定真实数据源,再交给 `SpringManagedTransaction`。 +4. **XA 数据源不要用 `datasource.*.init.schema` 建表**:脚本在 XA 连接池取出的连接上执行, + Atomikos 在事务管理器未运行时会话不提交,连接关闭时未提交的 DDL 会被回滚。本示例的 + H2 建表在 `config/H2SchemaInitializer` 中用普通连接完成;真实项目请直接连库执行 DDL, + 或交给 Flyway / Liquibase。 + +## 运行方式 + +```bash +# 单元测试(H2 内存库,无需 Docker) +./mvnw -pl spring-boot-4/tx-atomikos-sample test + +# 启动应用,然后 curl -X POST http://localhost:8080/order \ +# -H 'Content-Type: application/json' -d '{"userId":1,"amount":30.00}' +./mvnw -pl spring-boot-4/tx-atomikos-sample spring-boot:run +``` + +初始化数据由 `db/h2/schema-*.sql` 预置:`account(user_id = 1)` 的 `balance = 100.00`。 + +## 常见问题 + +- **`NoSuchMethodError: setReapTimeout(int)`**:Atomikos 6.0.0 起(jakarta 版本线)移除了 + `setReapTimeout`,dynamic-datasource 4.6.0 及更早版本在 Atomikos 6 下启动即失败 + ([baomidou/dynamic-datasource#822](https://github.com/baomidou/dynamic-datasource/issues/822)), + 需升级到包含该修复的版本(预计 4.7.0)。 +- **Atomikos 6 与 Spring Boot 3/4**:必须使用 `jakarta` classifier 的 + `transactions-jdbc` / `transactions-jta`;Atomikos 5 及更早只有 `javax` 构件。 +- **`uniqueResourceName` 冲突**:Atomikos 要求每个 XA 资源名唯一,dynamic-datasource 会自动 + 取数据源的 key 作为 `uniqueResourceName`,手工添加数据源时注意不要重名。 +- **事务日志**:Atomikos 会在工作目录写 `transaction-logs`,异常退出后重启会先做故障恢复, + 属预期行为。 diff --git a/spring-boot-4/tx-atomikos-sample/pom.xml b/spring-boot-4/tx-atomikos-sample/pom.xml new file mode 100644 index 0000000..46b45d9 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/pom.xml @@ -0,0 +1,89 @@ + + + + spring-boot-4-samples + com.baomidou + 1.0.0 + + 4.0.0 + + tx-atomikos-sample + + + 4.7.0 + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-validation + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + + + com.baomidou + dynamic-datasource-spring-boot4-starter + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + + + + com.atomikos + transactions-jdbc + jakarta + + + com.atomikos + transactions-jta + jakarta + + + + jakarta.transaction + jakarta.transaction-api + + + com.h2database + h2 + runtime + + + org.projectlombok + lombok + provided + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/AtomikosApplication.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/AtomikosApplication.java new file mode 100644 index 0000000..da8e4fa --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/AtomikosApplication.java @@ -0,0 +1,41 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos; + +import lombok.extern.slf4j.Slf4j; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Atomikos XA 分布式事务样例的启动类。 + * + *

{@code @MapperScan} 显式声明 {@code sqlSessionFactoryRef},指向本模块 {@link + * com.baomidou.samples.atomikos.config.MyBatisConfig} 中装配了 {@code AtomikosTransactionFactory} 的 + * SqlSessionFactory,同时避免 AOT 下 AUTOWIRE_BY_TYPE 装配丢失(JVM 行为不变)。 + */ +@Slf4j +@SpringBootApplication +@MapperScan( + value = "com.baomidou.samples.atomikos.mapper", + sqlSessionFactoryRef = "sqlSessionFactory") +public class AtomikosApplication { + + public static void main(String[] args) { + SpringApplication.run(AtomikosApplication.class, args); + log.info("open http://localhost:8080/swagger-ui.html"); + } +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/H2SchemaInitializer.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/H2SchemaInitializer.java new file mode 100644 index 0000000..20e8bfa --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/H2SchemaInitializer.java @@ -0,0 +1,73 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.config; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.support.EncodedResource; +import org.springframework.jdbc.datasource.init.ScriptUtils; +import org.springframework.stereotype.Component; + +/** + * H2 内存库的建表与预置数据。 + * + *

本示例没有使用 {@code spring.datasource.dynamic.datasource.*.init.schema}:那条路径是在 XA + * 连接池取出的连接上执行脚本,Atomikos 在事务管理器未运行时会话不提交,连接关闭时未提交的 DDL 会被回滚,表根本建不出来。这里用普通 DriverManager + * 连接(auto-commit)先把内存库和表 建好,Atomikos 连接池随后连上的是同一个 JVM 内的同名内存库。 + * + *

真实项目请直接连目标库执行 DDL,或交给 Flyway / Liquibase 管理。 + */ +@Slf4j +@Component +public class H2SchemaInitializer implements ApplicationRunner { + + private static final String USERNAME = "sa"; + + private static final String PASSWORD = ""; + + @Override + public void run(ApplicationArguments args) { + initDatabase("order", "db/h2/schema-order.sql"); + initDatabase("account", "db/h2/schema-account.sql"); + } + + private void initDatabase(String database, String scriptLocation) { + String url = "jdbc:h2:mem:" + database + ";DB_CLOSE_DELAY=-1"; + try (Connection connection = DriverManager.getConnection(url, USERNAME, PASSWORD)) { + ScriptUtils.executeSqlScript( + connection, + new EncodedResource(new ClassPathResource(scriptLocation), "UTF-8")); + try (ResultSet tables = + connection.getMetaData().getTables(null, null, "%", new String[] {"TABLE"})) { + while (tables.next()) { + log.info( + "h2 database [{}] table [{}] ready", + database, + tables.getString("TABLE_NAME")); + } + } + } catch (SQLException e) { + throw new IllegalStateException( + "failed to initialize h2 database [" + database + "]", e); + } + } +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/JtaConfig.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/JtaConfig.java new file mode 100644 index 0000000..2b9aa3e --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/JtaConfig.java @@ -0,0 +1,47 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.config; + +import com.atomikos.icatch.jta.UserTransactionManager; +import org.springframework.context.annotation.Bean; +import org.springframework.transaction.jta.JtaTransactionManager; + +/** + * 装配 Atomikos 的 JTA 事务管理器。 + * + *

Spring Boot 3 及以前会自动装配 Atomikos 的 {@code UserTransactionManager},但 Boot 4 起 JTA 自动配置只剩 JNDI + * 变体,需要自行声明;不声明时事务管理器会回退成 {@code JdbcTransactionManager},事务绑定的是主数据源上的单条连接, {@code @Transactional} + * 退化为单库本地事务,XA 两阶段提交根本不会发生。 + * + *

Atomikos 的事务日志默认落在工作目录的 {@code transaction-logs} 下。 + */ +@org.springframework.context.annotation.Configuration +public class JtaConfig { + + /** + * Atomikos 的事务管理器,同时实现 {@code jakarta.transaction.TransactionManager} 与 {@code + * jakarta.transaction.UserTransaction}。 + */ + @Bean(initMethod = "init", destroyMethod = "close") + public UserTransactionManager userTransactionManager() { + return new UserTransactionManager(); + } + + @Bean + public JtaTransactionManager transactionManager(UserTransactionManager userTransactionManager) { + return new JtaTransactionManager(userTransactionManager, userTransactionManager); + } +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/MyBatisConfig.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/MyBatisConfig.java new file mode 100644 index 0000000..26ca266 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/config/MyBatisConfig.java @@ -0,0 +1,47 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.config; + +import javax.sql.DataSource; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.springframework.context.annotation.Bean; + +/** + * Atomikos XA 场景下 MyBatis 的关键装配。 + * + *

多数据源 + XA 时,MyBatis 必须使用 dynamic-datasource 提供的 {@code + * com.baomidou.dynamic.datasource.tx.AtomikosTransactionFactory}:它在每次 MyBatis 事务开始时先按当前 {@code @DS} + * 线程变量确定真实数据源,再交给 SpringManagedTransaction, 而不是把动态路由数据源本身交给 MyBatis。 + * + *

声明名为 {@code sqlSessionFactory} 的 Bean 后,MybatisAutoConfiguration 的自动装配会退让, 由本配置全权负责。 + */ +@org.springframework.context.annotation.Configuration +public class MyBatisConfig { + + @Bean + public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { + Configuration configuration = new Configuration(); + configuration.setMapUnderscoreToCamelCase(true); + SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); + factoryBean.setDataSource(dataSource); + factoryBean.setTransactionFactory( + new com.baomidou.dynamic.datasource.tx.AtomikosTransactionFactory()); + factoryBean.setConfiguration(configuration); + return factoryBean.getObject(); + } +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/controller/OrderController.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/controller/OrderController.java new file mode 100644 index 0000000..0a9328f --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/controller/OrderController.java @@ -0,0 +1,55 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.controller; + +import com.baomidou.samples.atomikos.dto.PlaceOrderRequest; +import com.baomidou.samples.atomikos.entity.Order; +import com.baomidou.samples.atomikos.service.OrderService; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** 下单入口,可直接 POST /order 体验跨 XA 数据源的下单流程。 */ +@RestController +@RequestMapping("/order") +public class OrderController { + + private final OrderService orderService; + + public OrderController(OrderService orderService) { + this.orderService = orderService; + } + + @PostMapping + public String placeOrder(@RequestBody PlaceOrderRequest request) { + orderService.placeOrder(request); + return "ok"; + } + + @GetMapping("/{id}") + public Order get(@PathVariable Long id) { + return orderService.selectById(id); + } + + @GetMapping + public List list() { + return orderService.selectAll(); + } +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/dto/PlaceOrderRequest.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/dto/PlaceOrderRequest.java new file mode 100644 index 0000000..3d5afe1 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/dto/PlaceOrderRequest.java @@ -0,0 +1,30 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.dto; + +import java.math.BigDecimal; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** 下单请求。 */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class PlaceOrderRequest { + private Long userId; + private BigDecimal amount; +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/entity/Account.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/entity/Account.java new file mode 100644 index 0000000..b83b581 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/entity/Account.java @@ -0,0 +1,27 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.entity; + +import java.math.BigDecimal; +import lombok.Data; + +/** 账户,位于 account 数据源。 */ +@Data +public class Account { + private Long id; + private Long userId; + private BigDecimal balance; +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/entity/Order.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/entity/Order.java new file mode 100644 index 0000000..3d83a48 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/entity/Order.java @@ -0,0 +1,27 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.entity; + +import java.math.BigDecimal; +import lombok.Data; + +/** 订单,位于 order 数据源。 */ +@Data +public class Order { + private Long id; + private Long userId; + private BigDecimal amount; +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/exception/InsufficientBalanceException.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/exception/InsufficientBalanceException.java new file mode 100644 index 0000000..9dff3ec --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/exception/InsufficientBalanceException.java @@ -0,0 +1,23 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.exception; + +/** 余额不足,抛出后整个 XA 事务回滚。 */ +public class InsufficientBalanceException extends RuntimeException { + public InsufficientBalanceException(String message) { + super(message); + } +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/mapper/AccountMapper.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/mapper/AccountMapper.java new file mode 100644 index 0000000..1a082b3 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/mapper/AccountMapper.java @@ -0,0 +1,38 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.mapper; + +import com.baomidou.samples.atomikos.entity.Account; +import java.math.BigDecimal; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; +import org.apache.ibatis.annotations.Update; + +/** 账户 Mapper,默认路由到 account 数据源(由 Service 上的 {@code @DS} 决定)。 */ +public interface AccountMapper { + + @Select("select id, user_id, balance from account where user_id = #{userId}") + Account selectByUserId(@Param("userId") Long userId); + + /** 扣减余额,余额不足时影响行数为 0,由调用方转换为异常触发整体回滚。 */ + @Update( + "update account set balance = balance - #{amount} where user_id = #{userId} and balance >= #{amount}") + int deduct(@Param("userId") Long userId, @Param("amount") BigDecimal amount); + + /** 重置余额,仅供示例测试的用例之间清理数据使用。 */ + @Update("update account set balance = #{balance} where user_id = #{userId}") + void reset(@Param("userId") Long userId, @Param("balance") BigDecimal balance); +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/mapper/OrderMapper.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/mapper/OrderMapper.java new file mode 100644 index 0000000..5e7604a --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/mapper/OrderMapper.java @@ -0,0 +1,41 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.mapper; + +import com.baomidou.samples.atomikos.entity.Order; +import java.util.List; +import org.apache.ibatis.annotations.Delete; +import org.apache.ibatis.annotations.Insert; +import org.apache.ibatis.annotations.Options; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; + +/** 订单 Mapper,默认路由到 order 数据源(由 Service 上的 {@code @DS} 决定)。 */ +public interface OrderMapper { + + @Insert("insert into orders (user_id, amount) values (#{userId}, #{amount})") + @Options(useGeneratedKeys = true, keyProperty = "id") + int insert(Order order); + + @Select("select id, user_id, amount from orders where id = #{id}") + Order selectById(@Param("id") Long id); + + @Select("select id, user_id, amount from orders") + List selectAll(); + + @Delete("delete from orders") + int deleteAll(); +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/service/AccountService.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/service/AccountService.java new file mode 100644 index 0000000..278d170 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/service/AccountService.java @@ -0,0 +1,57 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.service; + +import com.baomidou.dynamic.datasource.annotation.DS; +import com.baomidou.samples.atomikos.entity.Account; +import com.baomidou.samples.atomikos.exception.InsufficientBalanceException; +import com.baomidou.samples.atomikos.mapper.AccountMapper; +import java.math.BigDecimal; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +/** 账户服务,所有方法都路由到 account 数据源。 */ +@Slf4j +@Service +public class AccountService { + + private final AccountMapper accountMapper; + + public AccountService(AccountMapper accountMapper) { + this.accountMapper = accountMapper; + } + + @DS("account") + public Account selectByUserId(Long userId) { + return accountMapper.selectByUserId(userId); + } + + /** 扣减余额;余额不足时抛出运行时异常,由调用方所在的 XA 事务整体回滚。 */ + @DS("account") + public void deduct(Long userId, BigDecimal amount) { + int updated = accountMapper.deduct(userId, amount); + if (updated == 0) { + throw new InsufficientBalanceException("用户 " + userId + " 余额不足,无法扣减 " + amount); + } + log.info("账户 {} 扣减 {} 成功", userId, amount); + } + + /** 重置余额,仅供示例测试的用例之间清理数据使用。 */ + @DS("account") + public void reset(Long userId, BigDecimal balance) { + accountMapper.reset(userId, balance); + } +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/service/OrderService.java b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/service/OrderService.java new file mode 100644 index 0000000..6c4edc1 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/java/com/baomidou/samples/atomikos/service/OrderService.java @@ -0,0 +1,103 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.service; + +import com.atomikos.icatch.jta.UserTransactionManager; +import com.baomidou.dynamic.datasource.annotation.DS; +import com.baomidou.samples.atomikos.dto.PlaceOrderRequest; +import com.baomidou.samples.atomikos.entity.Order; +import com.baomidou.samples.atomikos.mapper.OrderMapper; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; + +/** + * 订单服务:下单流程跨越 order 与 account 两个 XA 数据源。 + * + *

这里用编程式 JTA({@code UserTransaction})而不是 Spring 的 {@code @Transactional},原因是 MyBatis-Spring 在 + * Spring 事务同步激活时会把整个事务复用同一个 SqlSession(连同同一个连接), 该连接在事务内第一条语句执行时才按当时的 {@code @DS} 确定数据源,之后的 + * {@code @DS} 切换全部 失效,跨库写入会集中打到第一个数据源上。编程式 JTA 不注册 Spring 事务同步,每次 mapper 调用 各自取连接并按当前 {@code @DS} + * 路由,Atomikos 自动把连接登记进当前 JTA 事务, {@code commit} 时对两个 XA 资源做两阶段提交。 + * + *

若业务只操作单库,仍然可以用 Spring 的 {@code @Transactional}(配合 JtaConfig 里的 JtaTransactionManager)。 + */ +@Slf4j +@Service +public class OrderService { + + private final OrderMapper orderMapper; + private final AccountService accountService; + private final UserTransactionManager userTransactionManager; + + public OrderService( + OrderMapper orderMapper, + AccountService accountService, + UserTransactionManager userTransactionManager) { + this.orderMapper = orderMapper; + this.accountService = accountService; + this.userTransactionManager = userTransactionManager; + } + + /** 下单:先写 order 数据源,再扣 account 数据源的余额,任意一步失败两个库一起回滚。 */ + @DS("order") + public void placeOrder(PlaceOrderRequest request) { + log.info("=============ORDER START================="); + try { + userTransactionManager.begin(); + log.info("收到下单请求, 用户:{}, 金额:{}, JTA 事务已开始", request.getUserId(), request.getAmount()); + Order order = new Order(); + order.setUserId(request.getUserId()); + order.setAmount(request.getAmount()); + orderMapper.insert(order); + log.info("订单已写入 order 数据源, id={}", order.getId()); + accountService.deduct(request.getUserId(), request.getAmount()); + userTransactionManager.commit(); + log.info("账户扣减完成,两个 XA 资源已统一提交"); + } catch (RuntimeException e) { + rollbackSafely(); + throw e; + } catch (Exception e) { + rollbackSafely(); + throw new IllegalStateException("JTA 事务提交失败", e); + } + log.info("=============ORDER END================="); + } + + private void rollbackSafely() { + try { + userTransactionManager.rollback(); + log.info("JTA 事务已回滚"); + } catch (Exception rollbackException) { + log.error("JTA 事务回滚失败", rollbackException); + } + } + + @DS("order") + public Order selectById(Long id) { + return orderMapper.selectById(id); + } + + @DS("order") + public List selectAll() { + return orderMapper.selectAll(); + } + + /** 清空订单,仅供示例测试的用例之间清理数据使用。 */ + @DS("order") + public void deleteAll() { + orderMapper.deleteAll(); + } +} diff --git a/spring-boot-4/tx-atomikos-sample/src/main/resources/application.yml b/spring-boot-4/tx-atomikos-sample/src/main/resources/application.yml new file mode 100644 index 0000000..d3f5a8d --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/resources/application.yml @@ -0,0 +1,35 @@ +spring: + datasource: + dynamic: + primary: order + # Atomikos XA 全局连接池参数,可在单个数据源下用同样的 key 覆盖 + atomikos: + min-pool-size: 1 + max-pool-size: 10 + borrow-connection-timeout: 30 + max-idle-time: 60 + maintenance-interval: 60 + datasource: + # driver-class-name 指向 XA 数据源类(不是普通 JDBC Driver), + # url / username / password 会原样交给 XA 数据源。 + # type 必须显式声明为 AtomikosDataSourceBean:Hikari 创建器优先级更高, + # type 缺省时会接管并把 XA 数据源类误当作 java.sql.Driver 加载而启动失败。 + # 换成 MySQL 时用 com.mysql.cj.jdbc.MysqlXADataSource, + # PostgreSQL 用 org.postgresql.xa.PGXADataSource。 + order: + type: com.atomikos.jdbc.AtomikosDataSourceBean + driver-class-name: org.h2.jdbcx.JdbcDataSource + url: jdbc:h2:mem:order;DB_CLOSE_DELAY=-1 + username: sa + password: "" + # 没有配 init.schema:XA 连接池内执行脚本不会被 Atomikos 提交, + # 建表改由 config/H2SchemaInitializer 用普通连接完成,详见其类注释。 + account: + type: com.atomikos.jdbc.AtomikosDataSourceBean + driver-class-name: org.h2.jdbcx.JdbcDataSource + url: jdbc:h2:mem:account;DB_CLOSE_DELAY=-1 + username: sa + password: "" +logging: + level: + com.baomidou: debug diff --git a/spring-boot-4/tx-atomikos-sample/src/main/resources/db/h2/schema-account.sql b/spring-boot-4/tx-atomikos-sample/src/main/resources/db/h2/schema-account.sql new file mode 100644 index 0000000..e365d0e --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/resources/db/h2/schema-account.sql @@ -0,0 +1,7 @@ +create table account ( + id bigint auto_increment primary key, + user_id bigint not null unique, + balance decimal(12,2) not null +); + +insert into account (user_id, balance) values (1, 100.00); diff --git a/spring-boot-4/tx-atomikos-sample/src/main/resources/db/h2/schema-order.sql b/spring-boot-4/tx-atomikos-sample/src/main/resources/db/h2/schema-order.sql new file mode 100644 index 0000000..ccf5a42 --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/main/resources/db/h2/schema-order.sql @@ -0,0 +1,5 @@ +create table orders ( + id bigint auto_increment primary key, + user_id bigint not null, + amount decimal(12,2) not null +); diff --git a/spring-boot-4/tx-atomikos-sample/src/test/java/com/baomidou/samples/atomikos/test/AtomikosSampleTest.java b/spring-boot-4/tx-atomikos-sample/src/test/java/com/baomidou/samples/atomikos/test/AtomikosSampleTest.java new file mode 100644 index 0000000..fefe1af --- /dev/null +++ b/spring-boot-4/tx-atomikos-sample/src/test/java/com/baomidou/samples/atomikos/test/AtomikosSampleTest.java @@ -0,0 +1,110 @@ +/* + * Copyright © ${project.inceptionYear} organization baomidou + * + * 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 com.baomidou.samples.atomikos.test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.atomikos.jdbc.AtomikosDataSourceBean; +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.baomidou.dynamic.datasource.ds.ItemDataSource; +import com.baomidou.samples.atomikos.dto.PlaceOrderRequest; +import com.baomidou.samples.atomikos.entity.Account; +import com.baomidou.samples.atomikos.entity.Order; +import com.baomidou.samples.atomikos.exception.InsufficientBalanceException; +import com.baomidou.samples.atomikos.service.AccountService; +import com.baomidou.samples.atomikos.service.OrderService; +import java.math.BigDecimal; +import java.util.Map; +import javax.sql.DataSource; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.jta.JtaTransactionManager; + +@SpringBootTest +class AtomikosSampleTest { + + private static final Long USER_ID = 1L; + + private static final BigDecimal INITIAL_BALANCE = new BigDecimal("100.00"); + + @Autowired private OrderService orderService; + + @Autowired private AccountService accountService; + + @Autowired private DynamicRoutingDataSource routingDataSource; + + @Autowired private PlatformTransactionManager transactionManager; + + @AfterEach + void cleanUp() { + orderService.deleteAll(); + accountService.reset(USER_ID, INITIAL_BALANCE); + } + + @Test + void datasourcesAreAtomikosXaAndJtaIsActive() { + Map dataSources = routingDataSource.getDataSources(); + assertThat(dataSources).containsOnlyKeys("order", "account"); + // 路由数据源里的每个条目都被 dynamic-datasource 包装成 ItemDataSource,剥开后才是 + // Atomikos 的 XA 连接池。 + assertThat(dataSources.values()) + .allMatch( + ds -> + ds instanceof ItemDataSource + && ((ItemDataSource) ds).getRealDataSource() + instanceof AtomikosDataSourceBean); + // classpath 上有 Atomikos 时 Spring Boot 自动装配 JtaTransactionManager, + // 普通 @Transactional 即由 Atomikos 以两阶段提交接管。 + assertThat(transactionManager).isInstanceOf(JtaTransactionManager.class); + } + + @Test + void placeOrderCommitsAcrossTwoXaResources() { + orderService.placeOrder(new PlaceOrderRequest(USER_ID, new BigDecimal("30.00"))); + + assertThat(orderService.selectAll()) + .hasSize(1) + .first() + .satisfies( + order -> { + assertThat(order.getUserId()).isEqualTo(USER_ID); + assertThat(order.getAmount()).isEqualByComparingTo("30.00"); + }); + Account account = accountService.selectByUserId(USER_ID); + assertThat(account.getBalance()).isEqualByComparingTo("70.00"); + } + + @Test + void placeOrderRollsBackBothXaResourcesWhenBalanceInsufficient() { + // 余额 100,扣减 500 必然失败:order 数据源里已插入的订单必须随 account 的回滚一起消失, + // 这正是 XA 两阶段提交与 @DSTransactional 本地事务的本质区别。 + assertThatThrownBy( + () -> + orderService.placeOrder( + new PlaceOrderRequest(USER_ID, new BigDecimal("500.00")))) + .isInstanceOf(InsufficientBalanceException.class); + + assertThat(orderService.selectAll()).isEmpty(); + Order order = orderService.selectById(1L); + assertThat(order).isNull(); + Account account = accountService.selectByUserId(USER_ID); + assertThat(account.getBalance()).isEqualByComparingTo(INITIAL_BALANCE); + } +}