springboot项目中双数据源的配置

springboot项目中双数据源的配置

@对于一个项目中我们可能会配置多个数据源的情况,因而在这里向大家具体的介绍下如何在项目中配置多个数据源。比如我们配置一个EHR数据源和一个YSJ数据源。

1.pom文件中引入德鲁伊(druid)的依赖
<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>druid</artifactId>
		    <version>1.1.12</version>
		</dependency>
2.在我们的项目启动类中我们需要禁用数据源的自动配置的禁用,同时我们需要注入相关的数据源到spring中形成bean对象。
package com.ylkz;
import com.alibaba.druid.pool.DruidDataSource;
import com.ylkz.base.ApplicationParent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.sql.DataSource;
//配置多数据源前禁用自动配置数据源
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@EnableFeignClients
@EnableTransactionManagement
@Configuration
public class ServiceDemandApplication extends ApplicationParent
{
    protected Logger logger = LoggerFactory.getLogger(ServiceDemandApplication.class);


	public static void main(String[] args) {
        SpringApplication.run( ServiceDemandApplication.class, args );
    }

    @Bean(name="ysjDataSource")
    @ConfigurationProperties(prefix = "druid.datasource.db-ysj")
    public DataSource ysjDataSource() {
        return new DruidDataSource();
    }
    
    @Bean(name="ehrDataSource")
    @ConfigurationProperties(prefix = "druid.datasource.db-ehr")
    public DataSource ehrDataSource() {
        return new DruidDataSource();
    }
}
3.分别为每个数据源创建一个Config,EHR数据源默认为MybatisConfig,YSJ数据源为MybatisConfig1。该配置文件是为了从sqlSessionFactory工厂中获取相应的数据源Dao层bean对象去连接数据库。
3.1 EHR数据源的配置
/**    
 * <p><b>Description: </b></p>
 * <p><b>Date:</b>  Oct 23, 2018 6:51:50 PM </p> 
 * <p><b>Remark:  </b></p>
 */ 
package com.ylkz.DbConfig;
import javax.sql.DataSource;
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.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
/**    
 * <p><b>Description: </b></p>
 * <p><b>Date:</b>  Oct 23, 2018 6:51:50 PM </p> 
 * <p><b>Remark: 凡注册到Spring容器内的bean,实现了EnvironmentAware接口重写setEnvironment方法后,
 * 				  在工程启动时可以获得application.properties的配置文件配置的属性值。 </b></p>
 * @author Sean.Wang  
 */
@Configuration
//此处的basePackages 扫描的是我们Dao接口的路径
@MapperScan(basePackages = {"com.ylkz.Mappers.EhrMapper"}, sqlSessionFactoryRef = "ehrSqlSessionFactory")
public class MybatisConfig implements EnvironmentAware {


    private Environment environment;
    
    @Bean(name = "ehrSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("ehrDataSource") DataSource dataSource) {
        try {
            ResourcePatternResolver resourcePatternResolver;
            resourcePatternResolver = new PathMatchingResourcePatternResolver();

            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);
             //这里获取的属性其实是mybatis配置文件中的内容,具体的在下面会讲到
            String typeAliasesPackage = environment.getProperty("mybatis.config.typeAliasesPackage");
            String mapperLocations = environment.getProperty("mybatis.config.mapper-locations");
            String configLocation = environment.getProperty("mybatis.config.configLocation");
//            System.out.println("======>" + typeAliasesPackage);
//            System.out.println("======>" + mapperLocations);
//            System.out.println("======>" + configLocation);

            bean.setTypeAliasesPackage(typeAliasesPackage);
            bean.setMapperLocations(resourcePatternResolver.getResources(mapperLocations));
            bean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
            return bean.getObject();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Bean
    public PlatformTransactionManager platformTransactionManager(@Qualifier("ehrDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

	/* (non-Javadoc)  
	 * <p>Description: </p>  
	 * @param arg0  
	 * @see org.springframework.context.EnvironmentAware#setEnvironment(org.springframework.core.env.Environment)  
	 */
	@Override
	public void setEnvironment(Environment arg0) {
		// TODO Auto-generated method stub
		this.environment = arg0;
	}
	
	@Bean(name = "ehrSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("ehrSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
3.2 YSJ数据源的配置
/**
 * <p><b>Description: </b></p>
 * <p><b>Date:</b>  Oct 23, 2018 6:51:50 PM </p>
 * <p><b>Remark:  </b></p>
 */
package com.ylkz.DbConfig1;
import javax.sql.DataSource;
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.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

/**
 * <p>
 * <b>Description: </b>
 * </p>
 * <p>
 * <b>Date:</b> Oct 23, 2018 6:51:50 PM
 * </p>
 * <p>
 * <b>Remark: 凡注册到Spring容器内的bean,实现了EnvironmentAware接口重写setEnvironment方法后,
 * 在工程启动时可以获得application.properties的配置文件配置的属性值。 </b>
 * </p>
 *
 * @author Sean.Wang
 */
@Configuration
@MapperScan(basePackages = {
        "com.ylkz.Mappers.YsjMapper"}, sqlSessionFactoryRef = "ysjSqlSessionFactory")
public class MybatisConfig1 implements EnvironmentAware {

    //	这里不能用自动注入,要用下面的方法手动指明配置
    // @Autowired
    // DataSource dataSource;

/*	@Bean(name = "ysjDataSource")
	@ConfigurationProperties(prefix = "druid.datasource.db-ysj")
	public DataSource dataSource() {
		return DataSourceBuilder.create().build();
	}*/

    private Environment environment;

    @Bean(name = "ysjSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("ysjDataSource") DataSource dataSource) {
        try {
            ResourcePatternResolver resourcePatternResolver;
            resourcePatternResolver = new PathMatchingResourcePatternResolver();

            SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
            bean.setDataSource(dataSource);

            String typeAliasesPackage = environment.getProperty("mybatis.config1.typeAliasesPackage");
            String mapperLocations = environment.getProperty("mybatis.config1.mapper-locations");
            String configLocation = environment.getProperty("mybatis.config1.configLocation");
            // System.out.println("======>" + typeAliasesPackage);
            // System.out.println("======>" + mapperLocations);
            // System.out.println("======>" + configLocation);

            bean.setTypeAliasesPackage(typeAliasesPackage);
            bean.setMapperLocations(resourcePatternResolver.getResources(mapperLocations));
            bean.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
            return bean.getObject();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Bean
    public PlatformTransactionManager platformTransactionManager(@Qualifier("ysjDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /*
     * (non-Javadoc) <p>Description: </p>
     *
     * @param arg0
     *
     * @see org.springframework.context.EnvironmentAware#setEnvironment(org.
     * springframework.core.env.Environment)
     */
    @Override
    public void setEnvironment(Environment arg0) {
        // TODO Auto-generated method stub
        this.environment = arg0;
    }

    @Bean(name = "ysjSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("ysjSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
4.从第三步时需要获取druid中双数据源相关配置,因而在这里我们说一说其相关的配置信息,在这里我们创建application-db.yml配置文件
# 数据库配置
druid:
  datasource:
    db-ehr:
      driverClassName: ${ehr.driverClassName}
      # 注意:allowMultiQueries=true 开启允许多条sql执行
      url: ${ehr.jdbcurl}
      username: ${ehr.username}
      password: ${ehr.password}
      #初始化连接数量,最大最小连接数
      initialSize: 5
      maxActive: 20
      minIdle: 5
      #获取连接等待超时的时间
      maxWait: 600000
      #超过时间限制是否回收
      removeAbandoned: true
      #超过时间限制多长
      removeAbandonedTimeout: 180
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 600000
      #配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      #用来检测连接是否有效的sql,要求是一个查询语句
      validationQuery: SELECT 1 FROM sys_user
      #申请连接的时候检测
      testWhileIdle: true
      #申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能
      testOnBorrow: false
      #归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能
      testOnReturn: false
      #打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 50
      #属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
      #监控统计用的filter:stat 日志用的filter:log4j 防御SQL注入的filter:wall
      filters: stat
    db-ysj:
      driverClassName: ${ysj.driverClassName}
      # 注意:allowMultiQueries=true 开启允许多条sql执行
      url: ${ysj.jdbcurl}
      username: ${ysj.username}
      password: ${ysj.password}
      #初始化连接数量,最大最小连接数
      initialSize: 5
      maxActive: 20
      minIdle: 5
      #获取连接等待超时的时间
      maxWait: 600000
      #超过时间限制是否回收
      removeAbandoned: true
      #超过时间限制多长
      removeAbandonedTimeout: 180
      #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      timeBetweenEvictionRunsMillis: 600000
      #配置一个连接在池中最小生存的时间,单位是毫秒
      minEvictableIdleTimeMillis: 300000
      #用来检测连接是否有效的sql,要求是一个查询语句
      validationQuery: SELECT 1 FROM code_post
      #申请连接的时候检测
      testWhileIdle: true
      #申请连接时执行validationQuery检测连接是否有效,配置为true会降低性能
      testOnBorrow: false
      #归还连接时执行validationQuery检测连接是否有效,配置为true会降低性能
      testOnReturn: false
      #打开PSCache,并且指定每个连接上PSCache的大小
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 50
      #属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:
      #监控统计用的filter:stat 日志用的filter:log4j 防御SQL注入的filter:wall
      filters: stat

mybatis:
  config:
    typeAliasesPackage: com.ylkz.Beans.Ehr  #此处是实体的具体扫描路径
    mapper-locations: classpath:mybatis/ehrMapper/*Mapper.xml #这里是具体的Mapper.xml文件的扫描地址
    configLocation: classpath:mybatis-spring.xml  #这里是mybatis的具体配置文件地址或者具体的配置文件
  config1:
    typeAliasesPackage: com.ylkz.Beans.Yjs
    mapper-locations: classpath:mybatis/ysjMapper/*Mapper.xml
    configLocation: classpath:mybatis-spring.xml
5.在上一部druid双数据源配置中引用到了mybatis的配置,这里是具体的描述信息mybatis-spring.xml,项目中直接引用的xml文件直接放在resources目录下。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <properties>
        <property name="dialect" value="mysql" />
    </properties>
    <settings>
        <!-- 这个配置使全局的映射器启用或禁用缓存。系统默认值是true,设置只是为了展示出来 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="lazyLoadingEnabled" value="false" />
        <!-- 允许或不允许多种结果集从一个单独的语句中返回(需要适合的驱动)。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!--使用列标签代替列名。不同的驱动在这方便表现不同。参考驱动文档或充分测试两种方法来决定所使用的驱动。 系统默认值是true,设置只是为了展示出来 -->
        <setting name="useColumnLabel" value="true" />
        <!--允许 JDBC 支持生成的键。需要适合的驱动。如果设置为 true 则这个设置强制生成的键被使用,尽管一些驱动拒绝兼容但仍然有效(比如
            Derby)。 系统默认值是false,设置只是为了展示出来 -->
        <setting name="useGeneratedKeys" value="false" />
        <!--配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 系统默认值是SIMPLE,设置只是为了展示出来 -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!--设置超时时间,它决定驱动等待一个数据库响应的时间。 系统默认值是null,设置只是为了展示出来 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>
    <!--<plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql" />
            <property name="offsetAsPageNum" value="true" />
            <property name="rowBoundsWithCount" value="true" />
            <property name="pageSizeZero" value="true" />
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>-->
</configuration>
在这里插入代码片

在本文中介绍了具体的Dao层对象创建的配置文件MybatisConfig,Druid双数据源的配置文件application-db.yml(其中讲述了实体entity,mapper文件sql语句的具体路径配置),mybatis的配置文件mybatis-spring.xml ,以及springboot项目中启动类的配置 。谢谢大家。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值