1. 程式人生 > >sping boot 配置多數據源

sping boot 配置多數據源

eid .com druid ring char type vendor manage ssi

spring boot 本身自帶對數據源的支持。 但在項目開發過程中,存在這種情況需要用到多數據源,用spring boot 自帶的數據源就不是那麽方便了。這裏有個實例實現spring boot 完成多數據源的配置。

項目的目錄結構是這樣的。
技術分享圖片

下面看看數據源配置

// 主數據源配置
package com.tansun.beanconfig.datasourse;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
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.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * 註:主程序使用數據源
 * @author kangx
 *
 */
@Configuration
@EnableAutoConfiguration
@MapperScan(basePackages = MainDSConfig.PACKAGE, sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MainDSConfig {
    // 精確到 master 目錄,以便跟其他數據源隔離,不同數據源掃描的mapper
        // 文件地址是不一樣的,如果放到統一路徑啟動會報生成bean沖突。
    static final String PACKAGE = "com.tansun.model.*.mapper";
    static final String MAPPER_LOCATION = "classpath:com/tansun/model/*/master/*.xml";

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String user;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClass;

    /**
     * 註:主數據源加@Primary 註解 表示當系統有多個datasource 滿足條件,
     * 默認使用@Primary標記的數據源
     * @return
     */
    @Bean(name = "masterDataSource")
    @Primary
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setDbType("oracle");
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource,
            @Qualifier("databaseIdProvider") DatabaseIdProvider databaseIdProvider)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setDatabaseIdProvider(databaseIdProvider);
        return sessionFactory.getObject();
    }

    @Bean(name = "masterSqlSessionTemplate")
    public SqlSessionTemplate outerSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("databaseIdProvider")
    public DatabaseIdProvider getDatabaseIdProvider() {
        DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties pro = new Properties();
        pro.setProperty("Oracle", "oracle");
        pro.setProperty("MySQL", "mysql");
        databaseIdProvider.setProperties(pro);
        return databaseIdProvider;
    }

}

// 從數據源配置

package com.tansun.beanconfig.datasourse;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
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.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
/**
 * 註:定時任務使用數據源
 * @author kangx
 */
@Configuration
@EnableAutoConfiguration
// import 表示引用主數據源的配置bean
@Import(value = { MainDSConfig.class })
@MapperScan(basePackages = RunTaskDSConfig.PACKAGE, sqlSessionTemplateRef = "runtaskSqlSessionTemplate")
public class RunTaskDSConfig {

    // 精確到 master 目錄,以便跟其他數據源隔離--這兒掃描的地址和主數據地址//不同
    static final String PACKAGE = "com.tansun.taskmodel.*.mapper";
    static final String MAPPER_LOCATION = "classpath:com/tansun/taskmodel/*/master/*.xml";

    @Value("${runtask.datasource.url}")
    private String url;

    @Value("${runtask.datasource.username}")
    private String user;

    @Value("${runtask.datasource.password}")
    private String password;

    @Value("${runtask.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "runtaskDataSource")
    public DataSource masterDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setDbType("mysql");
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "runtaskTransactionManager")
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean(name = "runtaskSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("runtaskDataSource") DataSource masterDataSource,
            @Qualifier("databaseIdProvider") DatabaseIdProvider databaseIdProvider)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setDatabaseIdProvider(databaseIdProvider);
        return sessionFactory.getObject();
    }

    @Bean(name = "runtaskSqlSessionTemplate")
    public SqlSessionTemplate outerSqlSessionTemplate(@Qualifier("runtaskSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean("runtaskDatabaseIdProvider")
    public DatabaseIdProvider getDatabaseIdProvider() {
        DatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties pro = new Properties();
        pro.setProperty("Oracle", "oracle");
        pro.setProperty("MySQL", "mysql");
        databaseIdProvider.setProperties(pro);
        return databaseIdProvider;
    }
}

數據源配置屬性文件
所在路徑
技術分享圖片

#數據庫配置
spring.datasource.driver-class-name=
spring.datasource.url=
spring.datasource.username=
spring.datasource.password=
spring.jpa.show-sql=true

#定時任務數據源配置
#runtask.datasource.url=jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8
#runtask.datasource.username=root
#runtask.datasource.password=root
#runtask.datasource.driverClassName=com.mysql.jdbc.Driver
runtask.datasource.driverClassName=
runtask.datasource.url=
runtask.datasource.username=
runtask.datasource.password=
runtask.jpa.show-sql=true

sping boot 配置多數據源