springboot 配置多数据源

Posted DuoBa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot 配置多数据源相关的知识,希望对你有一定的参考价值。

1、动态数据源配置在yml文件

spring:
  datasource:
      type: com.alibaba.druid.pool.DruidDataSource
      # 初始化Druid
      druid:
        primary:
        # mysql数据库接地址
          jdbc-url: jdbc:mysql://**:3306/primary_db?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true
          username: **
          password: **
          driver-class-name: com.mysql.cj.jdbc.Driver

        school:
          jdbc-url: jdbc:mysql://**:3306/school?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true
          username: **
          password: **
          driver-class-name: com.mysql.cj.jdbc.Driver

      initial-size: 5
        # 最小空闲连接数 默认:0
      min-idle: 5
      # 最大连接数  默认:8
      max-active: 20
      # 获取连接等待超时的时间(毫秒) 默认:-1
      max-wait: 60000
      # 查询超时时间(秒)
      query-timeout: 90
      # 用来检测连接是否有效的sql,要求是一个查询语句
      validation-query: SELECT 1 FROM DUAL
      # 申请连接时检测连接可用性 默认:false
      test-on-borrow: false
      # 归还连接检测 默认:false
      test-on-return: false
      # 超时是否检测连接可用性
      test-while-idle: true
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接 (毫秒)
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间(毫秒,默认30分钟)
      min-evictable-idle-time-millis: 300000
      # 通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat;日志用的filter:log4j;防御sql注入的filter:wall
      filters: stat,slf4j
      # 慢SQL记录 https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatFilter
      filter:
        stat:
          log-slow-sql: true
          slow-sql-millis: 2000
          db-type: mysql
          # SQL合并 默认:false
          merge-sql: false
        wall:
          config:
            delete-allow: false
            drop-table-allow: false
            multi-statement-allow: true
          enabled: false
          db-type: mysql

      # 是否缓存PreparedStatement. PSCache对支持游标的数据库性能提升巨大,比如说oracle.在mysql下建议关闭.
      pool-prepared-statements: false
      # 每个连接上PSCache的大小
      max-pool-prepared-statement-per-connection-size: 20
      # 合并多个DruidDataSource的监控数据
      use-global-data-source-stat: true

  2、数据源切换类 不同数据源的mapper类放不同的package

@Configuration
@MapperScan(basePackages = "com.rbt.pen.mapper.primary", sqlSessionTemplateRef = "primarySqlSessionTemplate")
public class PrimaryDataSourceConfig {
    /**
     * 创建 DataSource
     * @return
     */
    @Bean("primaryDataSource")
    @ConfigurationProperties("spring.datasource.druid.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 创建 SQL会话工厂
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean("primarySqlSessionFactory")
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 创建 事务管理器
     * @param dataSource
     * @return
     */
    @Bean("primaryTransactionManager")
    public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 创建用户 SqlSession模板
     * @param sqlSessionFactory
     * @return
     */
    @Bean("primarySqlSessionTemplate")
    public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
Configuration
@MapperScan(basePackages = "com.rbt.pen.mapper.school", sqlSessionTemplateRef = "schoolSqlSessionTemplate")
public class SchoolDataSourceConfig {
    /**
     * 创建 DataSource
     * @return
     */
    @Bean("schoolDataSource")
    @ConfigurationProperties("spring.datasource.druid.school")
    public DataSource schoolDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 创建 SQL会话工厂
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean("schoolSqlSessionFactory")
    public SqlSessionFactory schoolSqlSessionFactory(@Qualifier("schoolDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 创建 事务管理器
     * @param dataSource
     * @return
     */
    @Bean("schoolTransactionManager")
    public DataSourceTransactionManager schoolTransactionManager(@Qualifier("schoolDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 创建用户 SqlSession模板
     * @param sqlSessionFactory
     * @return
     */
    @Bean("schoolSqlSessionTemplate")
    public SqlSessionTemplate schoolSqlSessionTemplate(@Qualifier("schoolSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

  3、将自定义注解启动

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"com.rbt"})

public class PenApplication {

    public static void main(String[] args) {
        try{
            SpringApplication.run(PenApplication.class, args);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

以上是关于springboot 配置多数据源的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot启动报错“Consider defining a bean of type ‘xxx.mapper.UserMapper‘ in your configuration.“(代码片段

SpringBoot中表单提交报错“Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported“(代码片段

Atitit.兼具兼容性和扩展性的配置方案attilax总结

SpringBoot 部署 Jar 文件,瘦身优化指南 !

项目启动报错Failed to configure a DataSource: 'url' attribute is not specified and no embedde(代码片段

SpringBoot特性