dynamic datasource
导入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.6</version>
</dependency>
编写配置文件
spring:
datasource:
dynamic:
primary: ds1 # 设置默认的数据源或者数据源组,默认值即为master,如果你主从默认下主库的名称就是master可不定义此项。
strict: fasle # 严格匹配数据源,默认fasle,true未匹配到指定数据源的时候抛异常
datasource:
ds1:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://47.xxx.xx.xxx:3306/dynamic?characterEncoding=utf8&useSSL=false
ds2:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://47.xxx.xx.xxx:3307/dynamic?characterEncoding=utf8&useSSL=false
#......省略
#以上会配置一个默认库ds1,一个组slave下有两个子库ds1,ds2
如何使用
在service层方法上加上 @DS("xxx")注解即可指定数据库
@DS("ds1")
public User getByUserId1(String userId){
return userDao.getById(Integer.parseInt(userId));
}
@DS("ds2")
public User getByUserId2(String userId){
return userDao.getById(Integer.parseInt(userId));
}
@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注解即可
@DSTransactional
public void insertUserAll(String name,String age){
UserService userService = (UserService) AopContext.currentProxy();
userService.insertUserDs1(name,age);
userService.insertUserDs2(name,age);
}
如果该方法抛出异常则会回滚
标签:String,数据源,age,dynamic,name,ds1,连接,springboot From: https://www.cnblogs.com/maomao777/p/17073163.html