springboot+mybatisplus多数据源配置和使⽤⼀、第⼀种注解配置
摘⾃mybatisplus官⽹的动态切换数据源的模块:
特性
⽀持 数据源分组 ,适⽤于多种场景 纯粹多库 读写分离 ⼀主多从 混合模式。
⽀持数据库敏感配置信息 加密 ENC()。
⽀持每个数据库独⽴初始化表结构schema和数据库database。
⽀持⽆数据源启动,⽀持懒加载数据源(需要的时候再创建连接)。
⽀持 ⾃定义注解 ,需继承DS(3.2.0+)。
提供并简化对Druid,HikariCp,BeeCp,Dbcp2的快速集成。
提供对Mybatis-Plus,Quartz,ShardingJdbc,P6sy,Jndi等组件的集成⽅案。
提供 ⾃定义数据源来源 ⽅案(如全从数据库加载)。
提供项⽬启动后 动态增加移除数据源 ⽅案。
提供Mybatis环境下的 纯读写分离 ⽅案。
提供使⽤ spel动态参数 解析数据源⽅案。内置spel,session,header,⽀持⾃定义。
⽀持 多层数据源嵌套切换 。(ServiceA >>> ServiceB >>> ServiceC)。
提供 **基于seata的分布式事务⽅案。提供 本地多数据源事务⽅案。
约定
本框架只做 切换数据源 这件核⼼的事情,并不限制你的具体操作,切换了数据源可以做任何CRUD。
配置⽂件所有以下划线 _ 分割的数据源 ⾸部 即为组的名称,相同组名称的数据源会放在⼀个组下。
切换数据源可以是组名,也可以是具体数据源名称。组名则切换时采⽤负载均衡算法切换。
默认的数据源名称为 master ,你可以通过 spring.datasource.dynamic.primary 修改。
⽅法上的注解优先于类上注解。
DS⽀持继承抽象类上的DS,暂不⽀持继承接⼝上的DS。
1、因为是基于Mybatis-plus来进⾏多数据源切换的,所以先导⼊mybatis-plus的多数据源pom
引⼊依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
2、配置数据源
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
datasource:
master:
username: root
password: 123456
driver-class-name: sql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/master
slave_1:
username: root
password: 123456
driver-class-name: sql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/slave1
slave_2:
username: root
password: 123456
driver-class-name: sql.cj.jdbc.Driver
jdbctemplate查询一条数据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.pe=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.master.sql.cj.jdbc.Driver
spring.datasource.druid.master.url=jdbc:mysql://localhost:3306/master?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=fal 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.stWhileIdle=true
spring.datasource.druid.master.timeBetweenEvictionRunsMillis=60000
spring.datasource.druid.master.minEvictableIdleTimeMillis=300000
spring.datasource.pe=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.slave.sql.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.stWhileIdle=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(){
ate().build();
}
@Bean(name="masterSqlSessionFactory")
@Primary
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
Object();
}
@Bean("masterSqlSessionTemplate")
@Primary
public SqlSessionTemplate primarySqlSessiontemplate() throws Exception{
return new SqlSessionTemplate(sqlSessionFactory());
}
}
@MapperScan(basePackages = "com.hd.mapper.slave", sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class SlaveDataSourceConfig {
@Bean(name = "slaveDataSource")
@ConfigurationProperties(prefix="spring.datasource.druid.slave")
public DataSource dataSource(){
ate().build();
}
@Bean(name = "slaveSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory() throws Exception {
MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
Object();
}
@Bean("slaveSqlSessionTemplate")
@Primary
public SqlSessionTemplate secondSqlSessiontemplate() throws Exception{
return new SqlSessionTemplate(sqlSessionFactory());
}
}
3、新建两套mapper
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
@Mapper
public interface Teacher extends BaseMapper<Teacher> {
}
4、启动类中main⽅法使⽤使⽤exclude禁⽤默认加载的application.properties单数据源配置,以及关闭mybatisPlus的⼀些⾃动注⼊
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, MybatisPlusAutoConfigu public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
5、验证多数据源
@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<Student> studentList = studentService.list();
//查询teacher表所有的教师
List<Teacher> 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⾃带的⽅法不能访问,但能访问*l 中定义的⽅法或者接⼝注解的⾃定义sql的⽅法
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论