Spring-boot + atomikos + druid分布式事务配置

来源:互联网 发布:淘宝店铺设计师申请 编辑:程序博客网 时间:2021/02/25 06:30

Spring-boot + atomikos + druid分布式事务配置

1.额外依赖项

<dependency>    <groupId>javax.transaction</groupId>    <artifactId>jta</artifactId>    <version>1.1</version></dependency><dependency>    <groupId>com.atomikos</groupId>    <artifactId>transactions-jta</artifactId>    <version>4.0.4</version></dependency><dependency>    <groupId>com.atomikos</groupId>    <artifactId>transactions-jdbc</artifactId>    <version>4.0.4</version></dependency>

2.数据源配置(yml配置,有几个数据源配置几个数据源,这里使用阿里Druid数据库连接池)

datasource:  # 资源标识  uniqueResourceName: datasource1  # 数据源类名  xaDataSourceClassName: com.alibaba.druid.pool.xa.DruidXADataSource  # 数据源配置  xaProperties:    driverClassName: com.mysql.jdbc.Driver    url: @spring.datasource.url@    username: @spring.datasource.username@    password: @spring.datasource.password@    initialSize: 3    minIdle: 3    maxActive: 20    maxWait: 60000    timeBetweenEvictionRunsMillis: 60000    minEvictableIdleTimeMillis: 300000    validationQuery: SELECT 1    testWhileIdle: true    testOnBorrow: false    testOnReturn: false    poolPreparedStatements: true    maxPoolPreparedStatementPerConnectionSize: 20    filters: stat

3.数据源以及事物管理器注入

// 数据源有几个配置几个/** * 注入数据源 * @return */@Bean@ConfigurationProperties(prefix = "datasource")public DataSource regDataSource() {    return new AtomikosDataSourceBean();}/** * 注入事物管理器 * @return */@Bean(name = "xatx")public JtaTransactionManager regTransactionManager () {    UserTransactionManager userTransactionManager = new UserTransactionManager();    UserTransaction userTransaction = new UserTransactionImp();    return new JtaTransactionManager(userTransaction, userTransactionManager);}

4.注解使用

@Override@Transactional(transactionManager = "xatx", propagation = Propagation.REQUIRED, rollbackFor = { java.lang.RuntimeException.class })public XXX function() {}