springboot2 连接多数据源

废话不多说,直接把相关的配置代码信息贴出来,都是经过项目验证的,没有问题的。

数据库连接配置:

我使用的yml配置文件

spring:
  datasource:
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    filters: stat
    maxActive: 10
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
    #设置removeAbandoned="true"时,当连接池连接数到达(getNumIdle() < 2) and (getNumActive() > getMaxActive() - 3)  [空闲的连接小于2并且活动的连接大于(最大连接-3)] 时便会启动连接回收,
    #那种活动时间超过removeAbandonedTimeout="1800"的连接将会被回收,
    #同时如果logAbandoned="true"设置为true,程序在回收连接的同时会打印日志。
    #removeAbandoned是连接池的高级功能,理论上这中配置不应该出现在实际的生产环境,因为有时应用程序执行长事务,可能这种情况下,会被连接池误回收,该种配置一般在程序测试阶段,为了定位连接泄漏的具体代码位置,被开启。
    #生产环境中连接的关闭应该靠程序自己保证。
    #先关着
    druid:
      remove-abandoned: true
      log-abandoned: true
      remove-abandoned-timeout: 1800
      filters: wall,stat
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=10000

    shop:
      jdbc-url: jdbc:mysql://${server.ip}:3306/test1?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver

    shopdata:
      jdbc-url: jdbc:mysql://${server.ip}:3306/test2?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver

 以上的注意点是:

连接url要写成:jdbc-url

 

数据库连接扫描的配置类,一个数据库连接一个配置类。

config1

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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 org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.xxx.xxx.shop", sqlSessionFactoryRef = "shopSqlSessionFactory")
public class ShopDBSourceConfig {
    /**
     * //自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
     * // prefix 指向的是配置文件中的数据库连接额前缀信息
     */
    @Bean(name = "shopSource")
    @ConfigurationProperties("spring.datasource.shop")
    @Primary
    public DataSource shopDataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "shopSqlSessionFactory")
    @Primary//自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
    public SqlSessionFactory sqlSessionFactory(@Qualifier("shopSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/shop/*.xml"));
        return bean.getObject();
    }

    /**
     * 事物管理
     */
    @Bean(name = "shopTransactionManager")
    @Primary//自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
    public DataSourceTransactionManager shopTransactionManager(@Qualifier("shopSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "shopSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate shopSqlSessionTemplate(
            @Qualifier("shopSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

basePackages : DAO文件的存放路径(增删改查的接口)

config2

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.xxx.xxx.shopdata", sqlSessionFactoryRef = "shopdataSqlSessionFactory")
public class ShopDataDBSourceConfig {
    /**
     * //自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
     * // prefix 指向的是配置文件中的数据库连接额前缀信息
     */
    @Bean(name = "shopdataSource")
    @ConfigurationProperties(prefix = "spring.datasource.shopdata")
    public DataSource shopdataDataSource() {
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "shopdataSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("shopdataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapping/shopdata/*.xml"));
        return bean.getObject();
    }

    /**
     * 事物管理
     */
    @Bean(name = "shopdataTransactionManager")
    public DataSourceTransactionManager shopdataTransactionManager(@Qualifier("shopdataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "shopdataSqlSessionTemplate")
    public SqlSessionTemplate shopdataSqlSessionTemplate(
            @Qualifier("shopdataSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

 

使用数据库事务:

@Transactional(transactionManager = "shopTransactionManager", rollbackFor = Exception.class)

 

 

你可能感兴趣的:(springboot2多数据库)