1.需求
使用Springboot进行项目开发时,需要访问多个数据库,每个数据库都有各自的作用,需要将数据分开建表存储。
1)多数据源配置:两个库业务互不相干,a方法使用a库的数据,b方法使用b库的数据;
2)动态数据源配置:两个库业务有关联,如读写分离库。
2.解决
有两种方式:1)利用@MapperScan(basePackages = {"mapper文件路径的方式"}, sqlSessionFactoryRef = "sqlSessionFactory")实现,具体方法和步骤参见https://www.cnblogs.com/niumoo/p/14209663.htmlb
本文推荐第二种方式,可根据自身情况自由选择。
2)使用Mabatis-plus的拓展多数据源包可以轻松实现多数据源的配置,且不需要变换已经建好的项目目录结构和configration。
3.Mabatis-plus多数据源配置
1)关于Mybatis-plus
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。所以不必担心已经建好的项目使用Mabatis-plus会影响原来的的方法。
2)步骤
2.1 依赖删除:
引入 MyBatis-Plus
之后再次引入 MyBatis
以及 MyBatis-Spring
,会因版本差异导致的问题,所以先将依赖库中的Mabatis依赖删除。
2.1 依赖引入:
1)mabatis-plus依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>
版本号选用最新版本,这里我使用3.3.0;
2)多数据源拓展包引入
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.0</version>
</dependency>
2.2 创建配置类:
@Configuration
@MapperScan("com.example.demo.mapper")
public class MyBatisConfiguration {
}
让Springboot扫描到项目的mapper接口文件夹,如果在加入依赖前已有配置类则无需改动,保持不变即可。
2.3 在application.yml文件中配置datasource连接
1)新建application.yml文件
如果之前一直使用的时properties文件,则新建 application.yml文件,两个文件都会对项目进行配置。
2)在yml文件中添加如下数据源配置
spring:
datasource:
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver # 3.2.0开始支持SPI可省略此配置
slave_1:
url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
slave_2:
url: ENC(xxxxx) # 内置加密,使用请查看详细文档
username: ENC(xxxxx)
password: ENC(xxxxx)
driver-class-name: com.mysql.jdbc.Driver
#......省略
#以上会配置一个默认库master,一个组slave下有两个子库slave_1,slave_2
3)配置模式
# 多主多从 纯粹多库(记得设置primary) 混合配置
spring: spring: spring:
datasource: datasource: datasource:
dynamic: dynamic: dynamic:
datasource: datasource: datasource:
master_1: mysql: master:
master_2: oracle: slave_1:
slave_1: sqlserver: slave_2:
slave_2: postgresql: oracle_1:
slave_3: h2: oracle_2:
2.4 使用 @DS 切换数据源。
示例:在进行数据库操作的mapper接口上加注解即可实现对应数据库的操作。
@Repository
public interface IExhibitContentMapper {
@DS("exhibit_content")
int createExhibitContentTable(String tableName);
@DS("exhibit_content")
int insertExhibitContent(@Param("tableName") String table,@Param("part") String content);
@DS("exhibit_content")
int deleteExhibitContent(@Param("tableName") String table);
@DS("exhibit_content")
List<ExhibitContentVO> getExhibitContent(@Param("tableName") String table);
}
4.Mabatis-plus拓展多数据源使用规范
1)本框架只做 切换数据源 这件核心的事情,并不限制你的具体操作,切换了数据源可以做任何CRUD。
2)配置文件所有以下划线 _
分割的数据源 首部 即为组的名称,相同组名称的数据源会放在一个组下。
3)切换数据源可以是组名,也可以是具体数据源名称。组名则切换时采用负载均衡算法切换。
4)默认的数据源名称为 master ,你可以通过 spring.datasource.dynamic.primary
修改。
5)方法上的注解优先于类上注解。
6)DS支持继承抽象类上的DS,暂不支持继承接口上的DS。