一、第一种注解配置
摘自mybatisplus官网的动态切换数据源的模块:
_
分割的数据源 首部 即为组的名称,相同组名称的数据源会放在一个组下。spring.datasource.dynamic.primary
修改。1、因为是基于Mybatis-plus来进行多数据源切换的,所以先导入mybatis-plus的多数据源pom
引入依赖
com.baomidou
dynamic-datasource-spring-boot-starter
3.2.0
2、配置数据源
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
datasource:
master:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/master
slave_1:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/slave1
slave_2:
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/slave2
#......省略
#以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2
3、使用 @DS 切换数据源
@DS
可以注解在方法上和类上,同时存在则 方法注解优先于类上注解
。
强烈建议只注解在service实现上。
注解 | 结果 |
---|---|
没有@DS | 默认数据源 |
@DS(“dsName”) | dsName可以为组名也可以为具体某个库的名称 |
@Service
@DS("slave_1") //注解在类上
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
public List selectAll() {
return jdbcTemplate.queryForList("select * from user");
}
@Override
@DS("slave_2") //注解在方法上,指明使用数据源使用名字叫 slave_2 的数据源
public List selectByCondition() {
return jdbcTemplate.queryForList("select * from user where age >10");
}
}
二、第二种:代码配置
1、properties配置文件
#数据库配置
spring.datasource.druid.master.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.master.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.druid.master.url=jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.druid.master.username=db1
spring.datasource.druid.master.password=db1
spring.datasource.druid.master.initialSize=10
spring.datasource.druid.master.maxActive=100
spring.datasource.druid.master.minIdle=10
spring.datasource.druid.master.maxWait=60000
spring.datasource.druid.master.testWhileIdle=true
spring.datasource.druid.master.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.master.minEvictableIdleTimeMillis=300000
spring.datasource.druid.slave.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.slave.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.druid.slave.url=jdbc:mysql://localhost:3306/slave?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.druid.slave.username=db1
spring.datasource.druid.slave.password=db1
spring.datasource.druid.slave.initialSize=10
spring.datasource.druid.slave.maxActive=100
spring.datasource.druid.slave.minIdle=10
spring.datasource.druid.slave.maxWait=60000
spring.datasource.druid.slave.testWhileIdle=true
spring.datasource.druid.slave.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.slave.minEvictableIdleTimeMillis=300000
2、数据源配置
@Configuration
@MapperScan(basePackages="com.hd.mapper.master", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
@Bean(name = "masterDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.druid.master")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
@Bean(name="masterSqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
@Bean("masterSqlSessionTemplate")
@Primary
public SqlSessionTemplate primarySqlSessiontemplate() throws Exception{
return new SqlSessionTemplate(sqlSessionFactory());
}
}
@Configuration
@MapperScan(basePackages = "com.hd.mapper.slave", sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class SlaveDataSourceConfig {
@Bean(name = "slaveDataSource")
@ConfigurationProperties(prefix="spring.datasource.druid.slave")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
@Bean(name = "slaveSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
return sessionFactory.getObject();
}
@Bean("slaveSqlSessionTemplate")
@Primary
public SqlSessionTemplate secondSqlSessiontemplate() throws Exception{
return new SqlSessionTemplate(sqlSessionFactory());
}
}
3、新建两套mapper
@Mapper
public interface StudentMapper extends BaseMapper {
}
@Mapper
public interface Teacher extends BaseMapper {
}
4、启动类中main方法使用使用exclude禁用默认加载的application.properties单数据源配置,以及关闭mybatisPlus的一些自动注入
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, MybatisPlusAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5、验证多数据源
@RestController
@RequestMapping("/base")
public class BaseController {
@Autowired
private StudentService studentService;
@Autowired
private TeacherService teacherService;
@PostMapping("/addStudentAndTeacher")
public ResultMsg addStudentAndTeacher(String studentName,String teacherName){
//新增一个学生
Student student = new Student();
student.setName(studentName);
studentService.save(student);
//新增一个教师
Teacher teacher = new Teacher();
teacher.setName(teacherName);
teacherService.save(teacher);
return ResultMsg.ok();
}
@RequestMapping("/find")
public ResultMsg find(){
//查询student表所有的学生
List studentList = studentService.list();
//查询teacher表所有的教师
List teacherList = teacherService.list();
JSONObject data = new JSONObject();
data.put("studentList",studentList);
data.put("teacherList",teacherList);
ResultMsg resultMsg = new ResultMsg();
resultMsg.setData(data);
return resultMsg;
}
}
注:
SqlSessionFactoryBean需要改成MybatisSqlSessionFactoryBean,否则baseMapper自带的方法不能访问,但能访问*Mapper.xml中定义的方法或者接口注解的自定义sql的方法