Spring多数据源配置
Mybatis-Plus多数据源支持:https://baomidou.com/guides/dynamic-datasource/
引入依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
配置多数据库:
spring:
datasource:
dynamic:
primary: ds1 #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
ds1:
url: jdbc:mysql://localhost:3306/ds1database
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
ds2:
url: jdbc:mysql://localhost:3306/ds2database
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
使用:
@DS("ds1")
public void insertUserDs1(String name,String age) {
userDao.insertUserDs1(name,age);
}
@DS("ds2")
public void insertUserDs2(String name,String age) {
userDao.insertUserDs2(name,age);
}
@DSTransactional
public void insertUserAll(String name, String age){
UserService userService = (UserService) AopContext.currentProxy();
userService.insertUserDs1(name,age);
userService.insertUserDs2(name,age);
int i =1/0;
}