java多数据源整合,5分钟学会springboot整合多数据源解决分布式事务

一、前言

springboot整合多数据源解决分布式事务。

1.多数据源采用分包策略

2.全局分布式事务管理:jta-atomikos。

在此记录下,分享给大家。

二、springboot整合多数据源解决分布式事务

54e691c5ab1fca0dcc2bc2ab7f648a47.png1190000021395431?utm_source=tuicool

1、pom文件 依赖引入

org.springframework.boot

spring-boot-starter-parent

2.1.8.RELEASE

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-web

org.mybatis.spring.boot

mybatis-spring-boot-starter

1.1.1

mysql

mysql-connector-java

5.1.38

org.springframework.boot

spring-boot-starter-jta-atomikos

org.springframework.boot

spring-boot-configuration-processor

true

org.projectlombok

lombok

1.18.4

1190000021395431?utm_source=tuicool

2、 application.yml 新增配置

spring:

datasource:

## 用户数据库

user:

url: jdbc:mysql://127.0.0.1:3306/yys_user

username: root

password: 123456

borrowConnectionTimeout: 30

loginTimeout: 30

maintenanceInterval: 60

maxIdleTime: 60

maxLifetime: 20000

maxPoolSize: 25

minPoolSize: 3

uniqueResourceName: userDataSource

testQuery: select 1

## 订单数据库

order:

url: jdbc:mysql://127.0.0.1:3306/yys_order

username: root

password: 123456

borrowConnectionTimeout: 30

loginTimeout: 30

maintenanceInterval: 60

maxIdleTime: 60

maxLifeTime: 20000

maxPoolSize: 25

minPoolSize: 3

uniqueResourceName: orderDataSource

testQuery: select 1

1190000021395431?utm_source=tuicool

3、userConfig.java

@ConfigurationProperties(prefix = "spring.datasource.user")

@Data

public class UserConfig {

private String url;

private String userName;

private String password;

private int minPoolSize;

private int maxPoolSize;

private int maxLifeTime;

private int maxIdleTime;

private int loginTimeout;

private int maintenanceInterval;

private int borrowConnectionTimeout;

private String testQuery;

private String uniqueResourceName;

}

1190000021395431?utm_source=tuicool

4、userDataSourceConfig.java

/**

* 用户数据源

* Config

* @author yys

*/

@Configuration

@MapperScan(basePackages = "com.yys.user.mapper", sqlSessionTemplateRef = "userSqlSessionTemplate")

public class UserDataSourceConfig {

/**

* 创建 XADataSource

* @return

*/

@Bean("userDataSource")

public DataSource userDataSource(UserConfig userConfig) throws SQLException {

// 1、创建Mysql XADataSource

MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();

mysqlXaDataSource.setUrl(userConfig.getUrl());

mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

mysqlXaDataSource.setPassword(userConfig.getPassword());

mysqlXaDataSource.setUser(userConfig.getUserName());

mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

// 2、将本地事务注册到 Atomikos 全局事务

AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();

xaDataSource.setXaDataSource(mysqlXaDataSource);

xaDataSource.setUniqueResourceName(userConfig.getUniqueResourceName());

xaDataSource.setMinPoolSize(userConfig.getMinPoolSize());

xaDataSource.setMaxPoolSize(userConfig.getMaxPoolSize());

xaDataSource.setMaxLifetime(userConfig.getMaxLifeTime());

xaDataSource.setBorrowConnectionTimeout(userConfig.getBorrowConnectionTimeout());

xaDataSource.setLoginTimeout(userConfig.getLoginTimeout());

xaDataSource.setMaintenanceInterval(userConfig.getMaintenanceInterval());

xaDataSource.setMaxIdleTime(userConfig.getMaxIdleTime());

xaDataSource.setTestQuery(userConfig.getTestQuery());

return xaDataSource;

}

/**

* 创建 SQL会话工厂

* @param dataSource

* @return

* @throws Exception

*/

@Bean("userSqlSessionFactory")

public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

sqlSessionFactoryBean.setDataSource(dataSource);

return sqlSessionFactoryBean.getObject();

}

/**

* 创建用户 SqlSession模板

* @param sqlSessionFactory

* @return

*/

@Bean("userSqlSessionTemplate")

public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {

return new SqlSessionTemplate(sqlSessionFactory);

}

}

1190000021395431?utm_source=tuicool

5、orderConfig.java

@ConfigurationProperties(prefix = "spring.datasource.order")

@Data

public class OrderConfig {

private String url;

private String userName;

private String password;

private int minPoolSize;

private int maxPoolSize;

private int maxLifeTime;

private int maxIdleTime;

private int loginTimeout;

private int maintenanceInterval;

private int borrowConnectionTimeout;

private String testQuery;

private String uniqueResourceName;

}

1190000021395431?utm_source=tuicool

6、orderDataSourceConfig.java

/**

* 订单数据源

* Config

* @author yys

*/

@Configuration

@MapperScan(basePackages = "com.yys.order.mapper", sqlSessionTemplateRef = "orderSqlSessionTemplate")

public class OrderDataSourceConfig {

/**

* 创建 XADataSource

* @return

*/

@Bean("orderDataSource")

public DataSource orderDataSource(OrderConfig orderConfig) throws SQLException {

// 1、创建Mysql XADataSource

MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();

mysqlXaDataSource.setUrl(orderConfig.getUrl());

mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

mysqlXaDataSource.setPassword(orderConfig.getPassword());

mysqlXaDataSource.setUser(orderConfig.getUserName());

mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);

// 2、将本地事务注册到 Atomikos 全局事务

AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();

xaDataSource.setXaDataSource(mysqlXaDataSource);

xaDataSource.setUniqueResourceName(orderConfig.getUniqueResourceName());

xaDataSource.setMinPoolSize(orderConfig.getMinPoolSize());

xaDataSource.setMaxPoolSize(orderConfig.getMaxPoolSize());

xaDataSource.setMaxLifetime(orderConfig.getMaxLifeTime());

xaDataSource.setBorrowConnectionTimeout(orderConfig.getBorrowConnectionTimeout());

xaDataSource.setLoginTimeout(orderConfig.getLoginTimeout());

xaDataSource.setMaintenanceInterval(orderConfig.getMaintenanceInterval());

xaDataSource.setMaxIdleTime(orderConfig.getMaxIdleTime());

xaDataSource.setTestQuery(orderConfig.getTestQuery());

return xaDataSource;

}

/**

* 创建 SQL会话工厂

* @param dataSource

* @return

* @throws Exception

*/

@Bean("orderSqlSessionFactory")

public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception {

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

sqlSessionFactoryBean.setDataSource(dataSource);

return sqlSessionFactoryBean.getObject();

}

/**

* 创建订单 SqlSession模板

* @param sqlSessionFactory

* @return

*/

@Bean("orderSqlSessionTemplate")

public SqlSessionTemplate orderSqlSessionTemplate(@Qualifier("orderSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {

return new SqlSessionTemplate(sqlSessionFactory);

}

}

1190000021395431?utm_source=tuicool

7、MybatisController.java

/**

* 多数据源解决分布式事务测试

* Controller

* @author yys

*/

@RestController

@RequestMapping("/add")

public class MybatisController {

@Autowired

private UserService userService;

@Autowired

private OrderService orderService;

/**

* 新增用户并生成订单(解决分布式事务问题)

* @return

*/

@RequestMapping("/user")

public String addUser(String name, Integer age, Double amount, String address) {

return userService.addUser(name, age, amount, address) ? "success" : "fail";

}

}

1190000021395431?utm_source=tuicool

8、UserService.java

/**

* 用户管理

* Service

* @author yys

*/

@Service

public class UserService {

@Autowired

private UserMapper userMapper;

@Autowired

private OrderMapper orderMapper;

// 全局事务处理器

// 事务底层原理采用aop技术做增强

// 无需再指定某个事务管理器,全交给 Atomikos 全局事务

@Transactional

public Boolean addUser(String name, Integer age, Double amount, String address) {

// 操作用户库

int i = userMapper.addUser(name, age);

// 操作订单库

int j = orderMapper.addOrder(amount, address);

// 测试事务回滚(age = 0:回滚;age > 0:事务提交)

int flag = 1 / age;

return i > 0 && j > 0;

}

}

1190000021395431?utm_source=tuicool

9、UserMapper.java

/**

* 用户管理

* Mapper

* @author yys

*/

public interface UserMapper {

@Insert("INSERT INTO user VALUES (NULL, #{name}, #{age}, 1, NOW(), NOW())")

int addUser(@Param("name") String name, @Param("age") Integer age);

}

1190000021395431?utm_source=tuicool

10、OrderMapper.java

/**

* 订单管理

* Mapper

* @author yys

*/

public interface OrderMapper {

// order为数据库关键字,记得使用``

@Insert("INSERT INTO `order` VALUES (NULL, #{amount}, #{address}, 1, NOW(), NOW())")

int addOrder(@Param("amount") Double amount, @Param("address") String address);

}

1190000021395431?utm_source=tuicool

11、启动类

@SpringBootApplication

@MapperScan("com.yys.mapper")

public class YysApp {

public static void main(String[] args) {

SpringApplication.run(YysApp.class, args);

}

}

1190000021395431?utm_source=tuicool

12、初始化sql文件

-- Database:yys_user

DROP TABLE IF EXISTS `user`;

CREATE TABLE `user` (

`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'ID,自增列',

`name` varchar(32) NOT NULL COMMENT '用户名',

`age` int(11) NOT NULL COMMENT '用户年龄',

`status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态:-1-删除;1-正常;',

`create_time` datetime NOT NULL COMMENT '创建时间',

`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

-- Database:yys_order

DROP TABLE IF EXISTS `order`;

CREATE TABLE `order` (

`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT 'ID,自增列',

`amount` double(11,2) NOT NULL COMMENT '订单金额',

`address` varchar(32) NOT NULL COMMENT '地址',

`status` tinyint(2) NOT NULL DEFAULT '1' COMMENT '状态:-1-删除;1-正常;',

`create_time` datetime NOT NULL COMMENT '创建时间',

`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

1190000021395431?utm_source=tuicool

13、测试

http://localhost:8080/add/user?name=古猿&age=0&amount=12.02&address=南方

1190000021395431?utm_source=tuicool

a、页面结果 - 如下图所示 :

dcdcfe39a289aee36b006c70fb28d2c1.png1190000021395431?utm_source=tuicool

b、数据库结果 - 如下图所示 :

84b8238404963be0e54a7af238d647ce.png1190000021395431?utm_source=tuicool

1750c95812dc1a00913b93b37e1ef04b.png1190000021395431?utm_source=tuicool

http://localhost:8080/add/user?name=古猿&age=18&amount=12.02&address=南方

1190000021395431?utm_source=tuicool

a、页面结果 - 如下图所示 :

d11dc9f548d9d38d20005b685bf1eeff.png1190000021395431?utm_source=tuicool

b、数据库结果 - 如下图所示 :

f3c33a7aa11bceb0c31d142e118bf8b6.png1190000021395431?utm_source=tuicool

23d38ca4df6af68b22f13fb47c126a53.png

1190000021395431?utm_source=tuicool

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 首先,为了使用多数据源分布式事务,我们需要添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.6</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jta-atomikos</artifactId> </dependency> ``` 接下来,我们需要在application.properties文件中配置数据源和事务管理器: ```properties # 配置主数据源 spring.datasource.url=jdbc:mysql://localhost:3306/main_db?characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver # 配置从数据源 spring.datasource.slave.url=jdbc:mysql://localhost:3306/slave_db?characterEncoding=utf8&useSSL=false spring.datasource.slave.username=root spring.datasource.slave.password=root spring.datasource.slave.driver-class-name=com.mysql.jdbc.Driver # 配置Mybatis mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.example.entity # 配置Druid数据源 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.druid.initial-size=1 spring.datasource.druid.max-active=10 spring.datasource.druid.min-idle=1 spring.datasource.druid.max-wait=60000 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.test-while-idle=true spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false spring.datasource.druid.filters=stat,wall,log4j spring.datasource.druid.connection-properties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 # 配置事务管理器 spring.transaction.default-timeout=600 spring.transaction.rollback-on-commit-failure=true spring.transaction.allow-bean-definition-overriding=true spring.transaction.jta.registry-name=atomikos spring.jta.enabled=true spring.jta.atomikos.connectionfactory.min-pool-size=5 spring.jta.atomikos.connectionfactory.max-pool-size=10 spring.jta.atomikos.connectionfactory.borrow-connection-timeout=30 spring.jta.atomikos.connectionfactory.max-idle-time=60 spring.jta.atomikos.connectionfactory.concurrency-level=100 ``` 然后,我们需要创建两个数据源的配置类,分别为主数据源和从数据源: ```java @Configuration @MapperScan(basePackages = "com.example.mapper.main", sqlSessionTemplateRef = "mainSqlSessionTemplate") public class MainDataSourceConfig { @Bean(name = "mainDataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource mainDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "mainSqlSessionFactory") public SqlSessionFactory mainSqlSessionFactory(@Qualifier("mainDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/main/*.xml")); return bean.getObject(); } @Bean(name = "mainTransactionManager") public DataSourceTransactionManager mainTransactionManager(@Qualifier("mainDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "mainSqlSessionTemplate") public SqlSessionTemplate mainSqlSessionTemplate(@Qualifier("mainSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` ```java @Configuration @MapperScan(basePackages = "com.example.mapper.slave", sqlSessionTemplateRef = "slaveSqlSessionTemplate") public class SlaveDataSourceConfig { @Bean(name = "slaveDataSource") @ConfigurationProperties(prefix = "spring.datasource.slave") public DataSource slaveDataSource() { return DruidDataSourceBuilder.create().build(); } @Bean(name = "slaveSqlSessionFactory") public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/slave/*.xml")); return bean.getObject(); } @Bean(name = "slaveTransactionManager") public DataSourceTransactionManager slaveTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "slaveSqlSessionTemplate") public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } } ``` 最后,我们需要在事务管理器上添加注解@EnableTransactionManagement,并在需要使用事务的方法上添加注解@Transactional: ```java @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Transactional(rollbackFor = Exception.class, transactionManager = "mainTransactionManager") @Override public void save(User user) { userMapper.insert(user); } @Transactional(rollbackFor = Exception.class, transactionManager = "slaveTransactionManager") @Override public User findById(int id) { return userMapper.selectByPrimaryKey(id); } } ``` 以上就是使用SpringBoot+Mybatis+druid多数据源分布式事务的基本步骤。 ### 回答2: Spring Boot是一个用于构建独立的、生产级的应用程序的框架。它简化了应用程序的开发过程,并通过自动配置来减少了繁琐的配置。MyBatis是一个ORM(对象关系映射)框架,它提供了将数据库操作映射到Java对象的功能。Druid是一种高性能的数据库连接池。 要在Spring Boot中使用MyBatis和Druid进行多数据源配置和分布式事务管理,可以按照以下步骤进行操作: 1. 添加依赖:在项目的pom.xml文件中,添加Spring Boot、MyBatis和Druid的依赖。 2. 配置数据源:在application.properties文件中,配置并命名多个数据源,设置数据库连接等信息。 3. 创建数据源配置类:创建一个配置类,使用@Configuration注解将其标记为配置类,并使用@ConfigurationProperties注解将数据源属性注入。 4. 创建数据源:根据配置类中的属性,创建多个数据源,并将其加入到数据源路由器中。 5. 配置MyBatis:创建一个配置类,使用@MapperScan注解设置MyBatis的mapper接口路径,并将数据源注入到SqlSessionFactory中。 6. 配置分布式事务:使用@EnableTransactionManagement注解启用事务管理,并配置事务管理器。 7. 编写数据库操作代码:在mapper接口中定义数据库操作方法,并在Service层中调用这些方法进行数据库操作。 通过以上步骤,你就可以在Spring Boot项目中完成MyBatis和Druid的多数据源配置和分布式事务管理。不过需要注意的是,使用多数据源分布式事务会增加项目的复杂性和性能开销,所以在使用之前需要仔细考虑是否真正需要这些功能。 ### 回答3: Spring Boot是一种快速构建Java应用程序的框架,MyBatis是一种流行的Java持久化框架,Druid是一种高性能的数据库连接池。本文将介绍如何在Spring Boot中使用MyBatis和Druid来实现多数据源分布式事务。 要使用多个数据源,我们首先需要配置多个数据源。在Spring Boot中,我们可以通过在application.properties或者application.yml文件中配置多个数据源的连接信息。我们需要为每个数据源指定不同的URL、用户名和密码。然后,我们可以使用@Primary和@Qualifier来指定主数据源和其他数据源。 在配置数据源后,我们需要配置MyBatis来使用这些数据源。我们可以通过创建多个SqlSessionFactory来实现多数据源,然后在每个SqlSessionFactory中设置相应的数据源。我们还可以使用@MapperScan注解来自动扫描和注册Mapper接口。 在使用MyBatis和多个数据源时,我们可能会遇到事务管理的问题。为了解决这个问题,我们可以使用Spring Boot提供的@Transactional注解来标记需要进行事务管理的方法,然后Spring Boot会自动为我们处理事务。对于需要跨多个数据源进行事务管理的情况,我们可以使用JTA(Java Transaction API)实现分布式事务。在Spring Boot中,我们可以使用Atomikos或Bitronix等JTA提供商来实现分布式事务。 总结起来,使用Spring Boot、MyBatis和Druid,我们可以很容易地实现多数据源分布式事务。通过正确配置数据源和使用相关注解,我们可以在几分钟内完成这些任务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值