Springboot多数据源配置

本次文档以oracle数据库配置为案例,在Springboot项目中,使用alibaba完成多数据源配置。先附上目录结构。

Springboot多数据源配置

配置多数据源有两种,一种是通过命名规则来自动选择数据库连接池。另一种是制定固定目录下的文件是使用哪个连接池。本人倾向于第二种,这样要更换连接池的时候只需要移动文件目录即可。而且也不用在mapper文件限制了程序员的命名。

在这次案例中,我指定mapper下每个文件夹就是一个连接池,hczz是一个连接池,jq是一个连接池。

一、配置文件添加相关配置

Springboot多数据源配置

相关参数如果不明白意思,可以百度一下,敲打过程中没有代码提示也不用紧张。

在这里,以防配置错误,贴上代码。

spring:

datasource:

    type: com.alibaba.druid.pool.DruidDataSource

    driver-class-name: oracle.jdbc.OracleDriver

druid:

   hczz:

      url:

      username:

      password:

     initial-size: 5

      max-active: 5

      min-idle: 5

     max-wait: 60000

     pool-prepared-statements: true

     max-pool-prepared-statement-per-connection-size: 20

     validation-query: SELECT 1 FROM DUAL

     test-while-idle: true

      test-on-borrow: false

      time-between-eviction-runs-millis: 300000

      soft-min-evictable-idle-time-millis: 600000

 备注:

1.hczz即是第一个数据库,也是主数据库,可自己定义名字

2.以下两句必须要配置,不然8小时后,或者更短,系统将会因为数据库没有正常关闭而引起宕机

time-between-eviction-runs-millis: 300000

   soft-min-evictable-idle-time-millis: 600000

 

二、配置数据源

备注:配置数据源要至少要配置一个主数据源,副数据源可多个

2.1配置主数据库连接池

Springboot多数据源配置

注意细节!注意细节!

@Configuration

@MapperScan(basePackages = "com.ccf.mapper.hczz",sqlSessionTemplateRef = "hczzSqlSessionTemplate")

public class HczzDataSourceConfig {

 

@Bean("hczz")

@Primary

@ConfigurationProperties(prefix = "spring.dataSource.druid.hczz")

public DataSource hczzDataSource(){

System.out.println("hczz DataSource");

return DataSourceBuilder.create().build();

}

 

@Bean("hczzSqlSessionFactory")

@Primary

public SqlSessionFactory sqlSessionFactory(@Qualifier("hczz") DataSource dataSource)throws Exception{

SqlSessionFactoryBean bean = new SqlSessionFactoryBean();

bean.setDataSource(dataSource);

bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/hczz/*.xml"));

bean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));

return bean.getObject();

}

 

@Bean("hczzTransactionManager")

@Primary

public DataSourceTransactionManager transactionManager(@Qualifier("hczz") DataSource dataSource) throws Exception{

return new DataSourceTransactionManager(dataSource);

}

 

@Bean("hczzSqlSessionTemplate")

@Primary

public SqlSessionTemplate sqlSessionTemplate(@Qualifier("hczzSqlSessionFactory") SqlSessionFactory sqlSessionFactory)throws Exception{

return new SqlSessionTemplate(sqlSessionFactory);

}

}

 

2.2配置副连接池

配置多副连接池有的是使用通配的方式注入,这样就不用写太多的配置文件,但由于本人在配置的过程中遇到一些问题,而且如果是有mysql连接池,也有oracle连接池,这样要指定不同的配置文件会比较麻烦。项目需要也不会一次性太多连接池,太多连接池那还不如开多个项目实现业务分离。

 

 

配置文件的配置跟主数据源配置一样。这里省略。

 

Springboot多数据源配置

 

跟主数据库相比,少了@Primary注解。

写得比较粗糙,有写得错误的或者有更好方法,欢迎评论、联系交流。

仅作为学习交流用途,禁止用于任何商业用途。

联系QQ:694335719

微信:lin69335719