多数据源管理在很多项目中都存在应用,怎么管理、用什么方法进行管理是需要公司内部进行讨论的问题。在之前的文章中实现了使用AbstractRoutingDataSource实现多数据源动态切换并使用实现Transaction、InvocationHandler来保证不同数据库切换的事务问题。
相关文章:SpringBoot中实现多数据源切换并保证事务一致
下面介绍使用dynamic-datasource-spring-boot-starter来实现多数据源的切换和事务保证。
引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
配置文件
server:
port: 8098
spring:
datasource:
dynamic:
enable: true # 启用动态数据源
primary: master # 设置默认的数据源
strict: false # 严格模式 默认 false 使用默认数据源 true 匹配不到会抛出异常
druid: # 配置全局连接池
initial-size: 1
min-idle: 1
max-active: 20
max-wait: 60000
# 间隔多久检测需要关闭的空闲链接
time-between-eviction-runs-millis: 60000
datasource:
master:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true&characterEncoding=utf-8&useAffectedRows=true&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: 123456
slave_1:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mycloud?useUnicode=true&characterEncoding=utf-8&useAffectedRows=true&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: 123456
服务类
@Service
public class T1ModelServiceImpl implements T1ModelService {
@Resource
private T1ModelMapper t1ModelMapper;
@Override
@DS("master")
public void insertT1Model(T1Model t1Model) {
t1ModelMapper.insert(t1Model);
}
}
@Service
public class TPayServiceImpl implements TPayService {
@Resource
private TPayMapper tPayMapper;
@Override
@DS("slave")
public void insertTPay(TPay pay) {
int i = 1/0;
tPayMapper.insert(pay);
}
}
@Service
public class DynamicDataSourceServiceImpl implements DynamicDataSourceService {
@Resource
private T1ModelService t1ModelService;
@Resource
private TPayService tPayService;
@Override
// @DSTransactional // 可以保证事务一致
public void insert() {
T1Model t1Model = new T1Model();
t1Model.setA(11112);
t1Model.setB(22222);
TPay tPay = new TPay();
tPay.setAmount(BigDecimal.ONE);
tPay.setPayNo("1234455");
tPay.setOrderNo("444444");
tPay.setUserId(12345678);
tPay.setCreateTime(new Date());
tPay.setUpdateTime(new Date());
tPay.setDeleted(new Byte("0"));
t1ModelService.insertT1Model(t1Model);
tPayService.insertTPay(tPay);
}
}
参考文章: