SSM+druid配置多数据源_Springboot学习

本文介绍如何在BootDo框架下配置多数据源以实现跨应用查询,详细讲解了YAML配置文件设置及Druid数据源配置过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本项目使用的bootdo框架,由于需要跨应用查一些信息,且不能调接口实现,最后决定配置多数据源。

首先关于application.yml,数据已脱敏

mybatis配置

mybatis: 
  configuration:
    map-underscore-to-camel-case: true
    jdbc-type-for-null: VARCHAR
  mapper-locations: classpath:mybatis/**/*Mapper.xml
  typeAliasesPackage: com.bootdo.**.domain

druid配置

spring:
  datasource:
    primary:  
      type: com.alibaba.druid.pool.DruidDataSource
      driverClassName: oracle.jdbc.driver.OracleDriver
      url: jdbc:oracle:thin:@10.14.14.14:1555/demo
      username: hahaha
      password: hahha
    second:  
      type: com.alibaba.druid.pool.DruidDataSource
      driverClassName: oracle.jdbc.driver.OracleDriver
      url: jdbc:oracle:thin:@10.10.10.10:1521/oradb
      username: hahaha
      password: hahaha

下面是上面的补充配置,需要的可以配置

initialSize: 1
      minIdle: 3
      maxActive: 20
      # 配置获取连接等待超时的时间
      maxWait: 60000
      # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 30000
      validationQuery: select 'x' from dual
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      # 打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 20
      # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,slf4j
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      # 合并多个DruidDataSource的监控数据
      #useGlobalDataSourceStat: true

接下来是DBConfig的两个类配置
主数据源

@SuppressWarnings("AlibabaRemoveCommentedCode")
@Configuration
@MapperScan(basePackages = { "com.bootdo.activiti.dao", "com.bootdo.blog.dao", "com.bootdo.common.dao",
        "com.bootdo.oa.dao", "com.bootdo.system.dao" }, sqlSessionTemplateRef = "baseSqlSessionTemplate")
public class DruidDBConfig {
    private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
    @Value("${mybatis.mapper-locations}")// 1
    String mapperLocations;
    @Bean(name = "baseDataSource") 
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    @Primary // 2
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "baseTransactionManager")
    @Primary
    public DataSourceTransactionManager setTransactionManager(@Qualifier("baseDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "baseSqlSessionFactory")
    @ConfigurationProperties(prefix = "mybatis")
    @Primary
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("baseDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        // bean.setConfiguration(getConfiguration());
        bean.setDataSource(dataSource);
         bean.setMapperLocations(
         new
                PathMatchingResourcePatternResolver().getResources(mapperLocations));
        return bean.getObject();
    }


    @Bean(name = "baseSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate setSqlSessionTemplate(
            @Qualifier("baseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    @Bean// 3
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        reg.addInitParameter("allow", ""); // 白名单
        return reg;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
        filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");
        filterRegistrationBean.addInitParameter("DruidWebStatFilter", "/*");
        return filterRegistrationBean;
    }
}

备注解释:

  1. SqlSessionFactory和SqlSessionFactoryBean不同,他只加载Configuration,其他不加载。
  2. 作为主数据源,必须要有@Primary这个注解
  3. 这个Bean和它以下的Bean都是为了开启druid自带的一个监控界面

副数据源

@SuppressWarnings("AlibabaRemoveCommentedCode")
@Configuration
@MapperScan(basePackages = "com.bootdo.esb.dao", sqlSessionTemplateRef = "esbSqlSessionTemplate")
public class DruidDBConfigESB {
    private Logger logger = LoggerFactory.getLogger(DruidDBConfigESB.class);
    @Value("${mybatis.mapper-locations}")
    String mapperLocations;

    @Bean(name = "esbDataSource") // 声明其为Bean实例
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "esbTransactionManager")
    public DataSourceTransactionManager setTransactionManager(@Qualifier("esbDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "esbSqlSessionFactory")
    @ConfigurationProperties(prefix = "mybatis")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("esbDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        // bean.setConfiguration(getConfiguration());
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        return bean.getObject();
    }

    @Bean(name = "esbSqlSessionTemplate")
    public SqlSessionTemplate setSqlSessionTemplate(
            @Qualifier("esbSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

注意:@MapperScan这个为必须配置项,否则还会调用默认的主数据源,配置就没有生效

结束
2018-02-09
一颗热爱学习的心

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值