有参照链接:SpringBoot配置多数据源的一款框架(dynamic-datasource-spring-boot-starter) - 编程宝库
场景:A公司为总公司,B公司为分公司,B公司上传的数据需要保存到A公司中。
application.yml的配置
java
spring:
datasource:
dynamic:
primary: mysql1
strict: false
datasource:
mysql1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/bn?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true
username: root
password: mima123
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
mysql2:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/bn_1?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false&allowMultiQueries=true
username: root
password: mima123
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
serviceImpl业务代码
java
@Override
public List<BnUser> getBnUser1() {
QueryWrapper<BnUser> b = new QueryWrapper<>();
b.eq("user_name","common");
List<BnUser> bnUser = bnUserMapper.selectList(b);
if (bnUser != null){
return bnUser;
}
return null;
}
//@DS("mysql2")
@Override
public List<BnUser> getBnUser2() {
QueryWrapper<BnUser> b = new QueryWrapper<>();
b.eq("user_name","common1");
List<BnUser> bnUser = bnUserMapper.selectList(b);
if (bnUser != null){
return bnUser;
}
return null;
}
controller的结果
java
@GetMapping("testMoreData")
public void testMoreData(){
List<BnUser> bnUser1 = bnUserService.getBnUser1();
System.out.println("bnuser1 ===== "+bnUser1);
List<BnUser> bnUser21 = bnUserService.getBnUser2();
System.out.println("bnuser2 ====== "+bnUser21);
/*DynamicDataSourceContextHolder.push("mysql1");
List<BnUser> users = bnUserService.getBnUser1();
DynamicDataSourceContextHolder.poll();
//这里切换了数据源
DynamicDataSourceContextHolder.push("mysql2");
List<BnUser> bnUser2 = bnUserService.getBnUser2();
DynamicDataSourceContextHolder.poll();
System.out.println(users + "=====" + bnUser2);*/
}
显示结果:
- serviceImpl文件并未打开 @DS -> bnuser1 有数据(mysql1);bnuser2 没有数据。
- serviceImpl文件并未打开 @DS -> controller中的注释打开 -> users 有数据(mysql1);bnUser2 有数据(mysql2)。
- serviceImpl文件打开 @DS -> bnuser1 有数据(mysql1);bnuser2有数据(mysql2)。