spring boot中如何使用多数据源配置

spring boot中如何使用多数据源配置

1、在我们使用编程过程中有时候需要使用不同的数据库呢,那就需要配置多数源,比如我们常用的mysql、pgsql、orecle等以及其他数据库今天我们就来用pgsql和orecle做多数据配置。
1、创建配置类 MybatisConfiguration
package **.task.config.mysql;
import com.github.pagehelper.PageHelper;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

/**

  • mybatis 配置数据源类

  • @author zhangsan

  • @date 2016年12月15日

  • @since 1.7
    */
    @Configuration(“mysqlCfg”)
    @EnableTransactionManagement
    @ConfigurationProperties(prefix = “spring.db_mysql”) //引用配置文件参数前缀
    public class MybatisConfiguration extends HikariConfig {
    @Value("${mybatis.mysql.xmlLocation}")
    private String xmlLocation;

    private String typeAliasesPackage;
      //配置数据源
    @Bean(“mysqlDataSource”)
    public DataSource dataSource(){
    /*
    HikariDataSource ds=HikariDataSource();
    ds.setJdbcUrl();
    ds.setConnectionTimeout();
    */
    return new HikariDataSource(this);
    }
      //配置Session工厂
    @Bean(name = “mysqlSqlSessionFactory”)
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier(“mysqlDataSource”)DataSource dataSource) {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    if(StringUtils.isNotBlank(typeAliasesPackage)){
    bean.setTypeAliasesPackage(typeAliasesPackage);
    }
    //分页插件
    PageHelper pageHelper = new PageHelper();
    Properties properties = new Properties();
    properties.setProperty(“reasonable”, “true”);
    properties.setProperty(“supportMethodsArguments”, “true”);
    properties.setProperty(“returnPageInfo”, “check”);
    properties.setProperty(“params”, “count=countSql”);
    pageHelper.setProperties(properties);
    //添加XML目录
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Interceptor[] plugins = new Interceptor[]{pageHelper};
    bean.setPlugins(plugins);
    try {

         bean.setMapperLocations(resolver.getResources(xmlLocation));
         return bean.getObject();
     } catch (Exception e) {
         e.printStackTrace();
         throw new RuntimeException(e);
     }
    

    }
      //mybatis会用到的SqlSession模板
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier(“mysqlSqlSessionFactory”) SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
    }
      //数据源事物配置
    @Bean
    public DataSourceTransactionManager transactionManager(@Qualifier(“mysqlDataSource”) DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
    }

}
2、配置文件如下。
spring:
application:
name: **-task
jackson:
date-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
default-property-inclusion: non_null
db_mysql:
name: DEV_MYSQL

    #LOCAL
    jdbc-url: jdbc:mysql://${MYSQL_HOST:192.168.10.141}:${MYSQL_PORT:3306}/p2p?useUnicode=true&characterEncoding=UTF8
    driver-class-name: com.mysql.jdbc.Driver
    username: p2p
    password: p2p

    # Hikari connection pool
    type: com.zaxxer.hikari.HikariDataSource
    minimum-idle: 5
    maximum-pool-size:  15
    auto-commit:  true
    idle-timeout: 30000
    pool-name:  DatebookHikariCP
    max-lifetime: 1800000
    connection-timeout: 30000
    connection-test-query:  SELECT 1
    validation-timeout: 10000
db_pg:
    name: DEV_PG

    # JDBC config
    jdbc-url:  jdbc:postgresql://192.168.10.141:5432/log
    driver-class-name:  org.postgresql.Driver
    username: log
    password: log

    # Hikari connection pool
    type: com.zaxxer.hikari.HikariDataSource
    minimum-idle: 5
    maximum-pool-size:  15
    auto-commit:  true
    idle-timeout: 30000
    pool-name:  DatebookHikariCP
    max-lifetime: 1800000
    connection-timeout: 30000
    connection-test-query:  SELECT 1
    validation-timeout: 10000

3、配置扫描类。
package **.task.config.mysql;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

/**

  • mybatis mapper 扫描配置类

  • @author

  • @date 2018年05月15日
    */
    @Configuration(“mysqlMapper”)
    @AutoConfigureAfter(MybatisConfiguration.class)//init时指定先后顺序,这里是数据源在mybatis之前配置
    public class MapperConfiguration implements EnvironmentAware {

    private RelaxedPropertyResolver propertyResolver;

    private String basePackage;
    //这里为mybatis配置指定session工厂和Dao类基础包路径
    @Bean(“mysqlMapperScannerConfigurer”)
    public MapperScannerConfigurer mapperScannerConfigurer(Environment environment){

     MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
     mapperScannerConfigurer.setSqlSessionFactoryBeanName("mysqlSqlSessionFactory");
     mapperScannerConfigurer.setBasePackage(basePackage);
     return mapperScannerConfigurer;
    

    }

    //设置环境变量(引用配置文件中的)
    @Override
    public void setEnvironment(Environment environment) {
    this.propertyResolver = new RelaxedPropertyResolver(environment, null);
    this.basePackage = propertyResolver.getProperty(“mybatis.mysql.basepackage”);
    }
    }
    4、到这里就完成了,后面优化实际操作教程,时间冲忙,先到这里了。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值