springboot配置多數據源並集成Druid和mybatis的操作

可以是mysql,oracle等多種不同數據源

項目結構

在這裡插入圖片描述

註意:隻有@Primary的數據源所控制的mapper文件加註解@Mapper,否則mybatis無法切換掃描;即本文中的mapper/opener文件夾下mapper加註解

1、pom

驅動之外加入druid和mybatis等pom,整合mybatis自行搜索

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>1.1.23</version>
 </dependency>

2、properties配置

##################    JDBC 配置    ################
#資訊數據庫一配置
spring.datasource.druid.opener.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.druid.opener.url=jdbc:oracle:thin:@127.0.0.1:1521:wljrdb
spring.datasource.druid.opener.username=opener
spring.datasource.druid.opener.password=123456

#輿情數據庫二配置
spring.datasource.druid.yq.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.druid.yq.url=jdbc:oracle:thin:@127.0.0.1:1521:wljrdb
spring.datasource.druid.yq.username=YQ
spring.datasource.druid.yq.password=123456

#f10數據庫二配置
spring.datasource.druid.f10.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.druid.f10.url=jdbc:mysql://127.0.0.1:3306/iwin-f10?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2b8
spring.datasource.druid.f10.username=root
spring.datasource.druid.f10.password=123456

##########################  druid配置   ##########################
# 下面為連接池的補充設置,應用到上面所有數據源中# 初始化大小,最小,最大
##################    連接池配置    ################
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=5
spring.datasource.druid.max-wait=30000

spring.datasource.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.druid.validation-query-timeout=30000
# 配置監控統計攔截的filters,去掉後監控界面sql無法統計,'wall'用於防火墻
spring.datasource.druid.filters=stat,wall,log4j2
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

# 監控中心 如果設置瞭StatViewServlet,即配置瞭監控池認證,
# 要進監控池需要輸入http://127.0.0.1:8083/druid/login.html,如果沒配置,直接輸入http://127.0.0.1:8083/druid/即可
spring.datasource.druid.stat-view-servlet.enabled= true
spring.datasource.druid.stat-view-servlet.url-pattern= /druid/*
spring.datasource.druid.stat-view-servlet.reset-enable= true
spring.datasource.druid.stat-view-servlet.login-username= admin
spring.datasource.druid.stat-view-servlet.login-password= admin123
spring.datasource.druid.stat-view-servlet.allow= 127.0.0.1

3、配置文件

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
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;

/**
 * @Author: admin
 */
@Configuration
public class MultiDataSourceConfig {

    private final static Logger logger = LoggerFactory.getLogger(MultiDataSourceConfig.class);

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.opener")
    public DataSource openerDataSource(){
        logger.info("opener數據源初始化。。。");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.yq")
    public DataSource yqDataSource(){
        logger.info("YQ數據源初始化。。。");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.f10")
    public DataSource f10DataSource(){
        logger.info("f10數據源初始化。。。");
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public SqlSessionFactory openerSqlSessionFactory(@Qualifier("openerDataSource")DataSource openerDataSource) throws Exception{
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(openerDataSource);
        fb.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:/mybatis/opener/*.xml")
        );
        return fb.getObject();
    }

    @Bean
    public SqlSessionFactory yqSqlSessionFactory(@Qualifier("yqDataSource")DataSource yqDataSource) throws Exception{
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(yqDataSource);
        fb.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:/mybatis/yq/*.xml")
        );
        return fb.getObject();
    }

    @Bean
    public SqlSessionFactory f10SqlSessionFactory(@Qualifier("f10DataSource")DataSource f10DataSource) throws Exception{
        SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
        fb.setDataSource(f10DataSource);
        fb.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:/mybatis/f10/*.xml")
        );
        return fb.getObject();
    }

    @Bean(name="openerMapperScannerConfigurer")
    @Primary
    public MapperScannerConfigurer openerMapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("openerSqlSessionFactory");
        configurer.setBasePackage("com.cfzq.lz.mapper.opener");
        return configurer;
    }

    @Bean(name="yqMapperScannerConfigurer")
    public MapperScannerConfigurer yqMapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("yqSqlSessionFactory");
        configurer.setBasePackage("com.cfzq.lz.mapper.yq");
        return configurer;
    }

    @Bean(name="f10MapperScannerConfigurer")
    public MapperScannerConfigurer f10MapperScannerConfigurer(){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setSqlSessionFactoryBeanName("f10SqlSessionFactory");
        configurer.setBasePackage("com.cfzq.lz.mapper.f10");
        return configurer;
    }

    @Bean(name="openerTransactionManager")
    @Primary
    public DataSourceTransactionManager openerTransactionManager(@Qualifier("openerDataSource")DataSource openerDataSource) throws Exception{
        return new DataSourceTransactionManager(openerDataSource);
    }

    @Bean(name="yqTransactionManager")
    public DataSourceTransactionManager yqTransactionManager(@Qualifier("yqDataSource")DataSource yqDataSource) throws Exception{
        return new DataSourceTransactionManager(yqDataSource);
    }

    @Bean(name="f10TransactionManager")
    public DataSourceTransactionManager f10TransactionManager(@Qualifier("f10DataSource")DataSource f10DataSource) throws Exception{
        return new DataSourceTransactionManager(f10DataSource);
    }

}

代碼調用

很簡單,使用哪個數據源service註入哪個mapper就可以瞭
在這裡插入圖片描述

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: