码迷,mamicode.com
首页 > 编程语言 > 详细

springboot 配置多数据源

时间:2020-01-15 11:42:59      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:lib   ida   new   常用   sql   tst   gap   会话   serve   

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 配置多数据源

标签:lib   ida   new   常用   sql   tst   gap   会话   serve   

原文地址:https://www.cnblogs.com/ampl/p/12195562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!