springboot-整合多数据源配置
本文内容纲要:
-简介
-一、表结构
-二、多数据源整合
-1.springboot+mybatis使用分包方式整合
-2.springboot+druid+mybatisplus使用注解整合
简介
主要介绍两种整合方式,分别是springboot+mybatis使用分包方式整合,和springboot+druid+mybatisplus使用注解方式整合。
一、表结构
在本地新建两个数据库,名称分别为db1
和db2
,新建一张user
表,表结构如下:
SQL代码:
CREATETABLE`user`(
`id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'主键',
`name`varchar(25)NOTNULLCOMMENT'姓名',
`age`int(2)DEFAULTNULLCOMMENT'年龄',
`sex`tinyint(1)NOTNULLDEFAULT'0'COMMENT'性别:0-男,1-女',
`addr`varchar(100)DEFAULTNULLCOMMENT'地址',
PRIMARYKEY(`id`)
)ENGINE=InnoDBAUTO_INCREMENT=2DEFAULTCHARSET=utf8
二、多数据源整合
1.springboot+mybatis使用分包方式整合
1.1主要依赖包
- spring-boot-starter-web
- mybatis-spring-boot-starter
- mysql-connector-java
- lombok
pom.xml
文件如下:
<?xmlversion="1.0"encoding="UTF-8"?>
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/><!--lookupparentfromrepository-->
</parent>
<groupId>com.example</groupId>
<artifactId>multipledatasource</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>multipledatasource</name>
<description>DemoprojectforSpringBoot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!--spring依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2application.yml配置文件
server:
port:8080#启动端口
spring:
datasource:
db1:#数据源1
jdbc-url:jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username:root
password:root
driver-class-name:com.mysql.cj.jdbc.Driver
db2:#数据源2
jdbc-url:jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username:root
password:root
driver-class-name:com.mysql.cj.jdbc.Driver
注意事项
- 各个版本的springboot配置datasource时参数有所变化,例如低版本配置数据库url时使用url属性,高版本使用jdbc-url属性,请注意区分。
1.3建立连接数据源的配置文件
第一个配置文件
@Configuration
@MapperScan(basePackages="com.example.multipledatasource.mapper.db1",sqlSessionFactoryRef="db1SqlSessionFactory")
publicclassDataSourceConfig1{
@Primary//表示这个数据源是默认数据源,这个注解必须要加,因为不加的话spring将分不清楚那个为主数据源(默认数据源)
@Bean("db1DataSource")
@ConfigurationProperties(prefix="spring.datasource.db1")//读取application.yml中的配置参数映射成为一个对象
publicDataSourcegetDb1DataSource(){
returnDataSourceBuilder.create().build();
}
@Primary
@Bean("db1SqlSessionFactory")
publicSqlSessionFactorydb1SqlSessionFactory(@Qualifier("db1DataSource")DataSourcedataSource)throwsException{
SqlSessionFactoryBeanbean=newSqlSessionFactoryBean();
bean.setDataSource(dataSource);
//mapper的xml形式文件位置必须要配置,不然将报错:nostatement(这种错误也可能是mapper的xml中,namespace与项目的路径不一致导致)
bean.setMapperLocations(newPathMatchingResourcePatternResolver().getResources("classpath*:mapping/db1/*.xml"));
returnbean.getObject();
}
@Primary
@Bean("db1SqlSessionTemplate")
publicSqlSessionTemplatedb1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory")SqlSessionFactorysqlSessionFactory){
returnnewSqlSessionTemplate(sqlSessionFactory);
}
}
第二个配置文件
@Configuration
@MapperScan(basePackages="com.example.multipledatasource.mapper.db2",sqlSessionFactoryRef="db2SqlSessionFactory")
publicclassDataSourceConfig2{
@Bean("db2DataSource")
@ConfigurationProperties(prefix="spring.datasource.db2")
publicDataSourcegetDb1DataSource(){
returnDataSourceBuilder.create().build();
}
@Bean("db2SqlSessionFactory")
publicSqlSessionFactorydb1SqlSessionFactory(@Qualifier("db2DataSource")DataSourcedataSource)throwsException{
SqlSessionFactoryBeanbean=newSqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setMapperLocations(newPathMatchingResourcePatternResolver().getResources("classpath*:mapping/db2/*.xml"));
returnbean.getObject();
}
@Bean("db2SqlSessionTemplate")
publicSqlSessionTemplatedb1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory")SqlSessionFactorysqlSessionFactory){
returnnewSqlSessionTemplate(sqlSessionFactory);
}
}
1.4具体实现
项目结构如下:
注意事项
- 在service层中根据不同的业务注入不同的dao层
- 如果是主从复制--读写分离:比如db1中负责增删改,db2中负责查询。但是需要注意的是负责增删改的数据库必须是主库(master)
2.springboot+druid+mybatisplus使用注解整合
2.1主要依赖包
- spring-boot-starter-web
- mybatis-plus-boot-starter
- dynamic-datasource-spring-boot-starter#配置动态数据源
- druid-spring-boot-starter#阿里的数据库连接池
- mysql-connector-java
- lombok
pom.xml
文件如下:
<?xmlversion="1.0"encoding="UTF-8"?>
<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/><!--lookupparentfromrepository-->
</parent>
<groupId>com.example</groupId>
<artifactId>mutipledatasource2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mutipledatasource2</name>
<description>DemoprojectforSpringBoot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>local1</id>
<properties>
<profileActive>local1</profileActive>
</properties>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<profile>
<id>local2</id>
<properties>
<profileActive>local2</profileActive>
</properties>
</profile>
</profiles>
</project>
2.2application.yml配置文件
server:
port:8080
spring:
datasource:
dynamic:
primary:db1#配置默认数据库
datasource:
db1:#数据源1配置
url:jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username:root
password:root
driver-class-name:com.mysql.cj.jdbc.Driver
db2:#数据源2配置
url:jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
username:root
password:root
driver-class-name:com.mysql.cj.jdbc.Driver
durid:
initial-size:1
max-active:20
min-idle:1
max-wait:60000
autoconfigure:
exclude:com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure#去除druid配置
-
DruidDataSourceAutoConfigure
会注入一个DataSourceWrapper
,其会在原生的spring.datasource
下找url,username,password等。动态数据源URL等配置是在dynamic下,因此需要排除,否则会报错。排除方式有两种,一种是上述配置文件排除,还有一种可以在项目启动类排除:@SpringBootApplication(exclude=DruidDataSourceAutoConfigure.class) publicclassApplication{ publicstaticvoidmain(String[]args){ SpringApplication.run(Application.class,args); } }
2.3给使用非默认数据源添加注解@DS
@DS
可以注解在方法上和类上,同时存在方法注解优先于类上注解。
注解在service实现或mapper接口方法上,不要同时在service和mapper注解。
@DS("db2")
publicinterfaceUserMapperextendsBaseMapper<User>{
}
@Service
@DS("db2")
publicclassModelServiceImplextendsServiceImpl<ModelMapper,Model>implementsIModelService{}
@Select("SELECT*FROMuser")
@DS("db2")
List<User>selectAll();
本文内容总结:简介,一、表结构,二、多数据源整合,1.springboot+mybatis使用分包方式整合,2.springboot+druid+mybatisplus使用注解整合,
原文链接:https://www.cnblogs.com/aizen-sousuke/p/11756279.html