在工作中,业务的发展或业务数据隔离的场景下,通常需要一个项目中引入多个数据源,但SpringBoot默认的自动化配置是单数据源的,在这里记录一个通过Spring分包的方式进行的多数据源配置
1.引入以下依赖
org.springframework.boot
spring-boot-starter-parent
2.3.0.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
com.baomidou
mybatis-plus-boot-starter
3.3.2
mysql
mysql-connector-java
runtime
com.alibaba
druid-spring-boot-starter
1.1.10
com.alibaba
fastjson
1.2.68
org.projectlombok
lombok
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-maven-plugin
2.application.yml修改
server:
port: 8751
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 5
min-idle: 5
max-active: 100
max-wait: 60000
im:
url: jdbc:mysql://192.168.16.112:3306/erlinyou_im?autoconnection&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username: root
password: 12345678
driver-class-name: com.mysql.cj.jdbc.Driver
user:
url: jdbc:mysql://192.168.16.114:3306/etravel?autoconnection&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username: root
password: 12345678
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
type-aliases-package: com.erlinyou.im.push.model
mapper-locations: classpath:mapper/*.xml
logging:
level:
com.erlinyou.im.push.mapper: debug
root: info
file:
name: log/sso.log
application定义了两个数据源,其他为mybaits-plus和spring的基本配置
3.启动类注解配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, MybatisPlusAutoConfiguration.class})
/**
* 使用exclude = {DataSourceAutoConfiguration.class}
* 禁用springboot默认加载的application.properties单数据源配置
* 关闭springBoot关于mybatisPlus的一些自动注入
*/
4.配置druid
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DruidConfig {
@Bean
public ServletRegistrationBean druidServlet () {
ServletRegistrationBean servletRegistrationBean
= new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "admin");
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.css, /druid/*");
return filterRegistrationBean;
}
}
5.配置包扫描配置数据源
@Configuration
@MapperScan(basePackages = "com.xxx.im.push.mapper.im",sqlSessionFactoryRef = "imSqlSessionFactory")
public class ImDataSourceConfig {
@Bean(name = "imDataSource")
@ConfigurationProperties("spring.datasource.druid.im")
public DataSource masterDataSource(){
// return DataSourceBuilder.create().build();
return new DruidDataSource();
}
@Bean(name = "imSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("imDataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
return sessionFactoryBean.getObject();
}
}
@ConfigurationProperties注解用于加载自定义的外部化配置
DataSourceBuilder.create().build();为hikari,也是SpringBoot默认的数据源,hikari也非常强大
new DruidDataSource();是druid数据源,这里采用druid数据源
以下为另一个数据源配置,同理
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "com.xxx.im.push.mapper.user",sqlSessionFactoryRef = "userSqlSessionFactory")
public class UserDataSourceConfig {
@Primary
@Bean(name = "userDataSource")
@ConfigurationProperties("spring.datasource.druid.user")
public DataSource masterDataSource(){
// return DataSourceBuilder.create().build();
return new DruidDataSource();
}
@Bean(name = "userSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);
return sessionFactoryBean.getObject();
}
}
总结一下
这种多数据源配置是通过mybaits动态扫描包的方式进行数据的切换,目前比较主流的还有通过AOP+ThreadLocal扫描注解的方式利用ThreadLocal对当前线程的数据源进行动态切换到达配置多数据源的目的,以及dynamic-datasource-spring-boot-starter 的方式,根据合适的业务场景来使用可以达到更好的效果,通过mybaits切换数据比较简单方便可以满足大部分对多数据源配置的业务场景