温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

sping boot 配置多数据源

发布时间:2020-06-26 10:18:19 来源:网络 阅读:1295 作者:飞鸟如林 栏目:开发技术

spring boot 本身自带对数据源的支持。 但在项目开发过程中,存在这种情况需要用到多数据源,用spring boot 自带的数据源就不是那么方便了。这里有个实例实现spring boot 完成多数据源的配置。

项目的目录结构是这样的。
sping 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;
    }
}

注 :
1主数据源配置 bean 上加@Primary标签,表示当找多个符合的匹配时,使用由 primary 标记的bean。 如果不加Primary标签启动会报错。
2 runtaskDatabaseIdProvider -> bean 配置是为了设置数据库兼容的设置。该处设置的值可以在, mapper文件中取到,用于标记不同的数据库,这一过程是有spring-mybatis 底层操作完成的。

数据源配置属性文件
所在路径
sping boot 配置多数据源

#数据库配置
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
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI