SpringBoot多数据原配置

SpringBoot配置多数据源

最近整理了下,分享下自己配置方法,后来发现了一些更加方便的多数据源配置,这里一起分享下。
由于orcale和sql server不予许通过pom.xml的依赖下载,所以可以去官网下载jar包,然后在pom.xml添加本地依赖

orcale驱动包官网下载
sqljdbc官网下载地址

orcale7驱动网盘链接 提取码: 8pnc
sqlserver驱动网盘链接 提取码: 7ix6

多数据源使用场景:之前公司的一个项目,为了同步两个不同数据库的数据;适用于多个数据源
主要用springboot+Mybatis
方法一:

  • 项目结构
    !在这里插入图片描述](https://img-blog.csdnimg.cn/20200909103644733.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTIyOTQzMA==,size_16,color_FFFFFF,t_70#pic_center)

  • 在pom.xml文件中需要添加一些依赖

<!-- mybatis -->
		<dependency>
		    <groupId>org.mybatis.spring.boot</groupId>
		    <artifactId>mybatis-spring-boot-starter</artifactId>
		    <version>2.1.0</version>
		</dependency>
		<!-- sqlserver -->
		<dependency>
		    <groupId>com.microsoft.sqlserver</groupId>
		    <artifactId>sqljdbc4</artifactId>
		    <version>4.0</version>
			<scope>system</scope>
			<systemPath>${project.basedir}/lib/sqljdbc4-4.0.jar</systemPath>
		</dependency>
		<!-- orcale -->
		<dependency>
	      <groupId>com.oracle</groupId>
	      <artifactId>ojdbc</artifactId>
	      <version>7</version>
	      <scope>system</scope>
	      <systemPath>${project.basedir}/lib/ojdbc-7.jar</systemPath>
	 	</dependency>

		 <!-- druid連接池 -->
		 <dependency> 
		 	<groupId>com.alibaba</groupId> 
			 <artifactId>druid-spring-boot-starter</artifactId> 
			 <version>1.1.10</version> 
		 </dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>

  • application.properties 配置两个数据源配置
server:
  port: 8080
spring:
  datasource:
    druid: 
       first: #主數據庫
            driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver
            #注意:在springboot2.0以上版本中,需要变为jdbc-url
            jdbc-url: jdbc:sqlserver://xx.xx.xx.xx:1433;instanceName=CNDVDB001S;DatabaseName=MESxxx
            username: root
            password: root
       second: #第二个数据库 
            driver-class-name: oracle.jdbc.driver.OracleDriver
            jdbc-url: jdbc:oracle:thin:@xx.xx.xx.xx:1521:PUBDV
            username: root
            password: root
#替换自己实际数据连接配置
mybatis:
    type-aliases-package: classpath:com.example.entity.Results
    mapper-locations: classpath:com.example.mapper/../*.xml
    

接下来需要进行数据源的配置,讲解下即将用到的注解(更多注解详情可以查看注解详解

@Configuration 注解在类上,定义该类为一个配置类,被注解的类内部包含有一个或多个被@Bean注解的方法,这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,并用于构建bean定义,初始化Spring容器。

@MapperScan指定要扫描的包,在此使用了basePackages和sqlSessionTemplateRef两个参数,
basePackages指定了扫描的mapper文件包,sqlSessionTemplateRef用来保证使用的SqlSession是和当前Spring的事务相关的

@Bean Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。
SpringIOC 容器管理一个或者多个bean,这些bean都需要在@Configuration注解下进行创建,在一个方法上使用@Bean注解就表明这个方法需要交给Spring进行管理。

@ConfigurationProperties该注解有一个prefix属性,通过指定的前缀,绑定配置文件中的配置;注解在类上,将外部配置文件加载进来,填充对象的对应字段的数据,然后供其他Bean使用。也可以注解在方法上,加载配置文件配置数据,进行使用;用法和@Value相似

@Primary自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者

  • 数据源配置代码
    DataSource1(first Datasource配置)
package com.example.config;

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.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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;

@Configuration
@MapperScan(basePackages = "com.example.mapper.first", sqlSessionTemplateRef  = "firstSqlSessionTemplate")
/**
*多数据源一定要配置sqlSessionTemplateRef 或者sqlSessionFactoryRef,否则无法获取对应的会话session
*/
public class DataSource1 {

	@Bean(name = "firstDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.druid.first")
	@Primary
	public DataSource testDataSource() {
		return DataSourceBuilder.create().build();
	}

	// 创建SqlSenssionFatocy
	@Bean(name = "firstSqlSessionFactory")
	@Primary
	public SqlSessionFactory testSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// 設置mybatis的xml所在位置
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:com.example.mapper/first/*.xml"));
		return bean.getObject();
	}

	// 創建事務
	@Bean(name = "firstTransactionManager")
	public DataSourceTransactionManager testTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	//创建SqlSessionTemplate,不在使用SqlSession默认的DefaultSqlSession,
	//线程是安全的,可以被多个baiDAO所共享使用,使用数据库连接池,减少数据库的连接次数
	@Bean(name = "firstSqlSessionTemplate")
	@Primary
	public SqlSessionTemplate testSqlSessionTemplate(
			@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

DataSource2(second Datasource配置)

package com.example.config;

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.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

@Configuration
@MapperScan(basePackages = "com.example.mapper.second", sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class DataSource2 {
	@Bean(name = "secondDaraSource")
	@ConfigurationProperties(prefix = "spring.datasource.druid.second")
	public DataSource testDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "secondSqlSessionFactory")
	public SqlSessionFactory testSqlSessionFactory(@Qualifier("secondDaraSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// 設置mybatis的xml所在位置
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:com.example.mapper/second/*.xml"));
		return bean.getObject();
	}

	@Bean(name = "secondTransactionManager")
	public DataSourceTransactionManager testTransactionManager(@Qualifier("secondDaraSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "secondSqlSessionTemplate")
	public SqlSessionTemplate testSqlSessionTemplate(
			@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}

这时数据源配置已经完成,使用直接在dao层使用@Autowired自动装配所需Mapper接口就行,

package com.example.dao;

import java.util.ArrayList;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.example.entity.YDGPSMT13;
import com.example.mapper.first.firstMapper;
import com.example.mapper.second.secondMapper;

@Repository
@MapperScan("com.example.mapper")
public class PQMDao {
	@Autowired(required=true)
	firstMapper firstMapper;

	public ArrayList<YDGPSMT13> getInfo() {
		return firstMapper.getInfo();
	}
	
	@Autowired(required=true)
	secondMapper secondMapper;
	
	public void insert(YDGPSMT13 vo) {
		secondMapper.insert(vo);
	}

	public Integer  getCount() {
		return firstMapper.getCount();
	}
}

至此,多数据源的处理数据的项目差不多就结束了。后来搜索了以下,还有更加方便的方法,使用的是MyBatis Plus和Dynamic Datasource的组合,在这里附带连接
SpringBoot多数据源解决方案
除此之外,在评论里发现了很好地整体依赖,MyBatis Plus和Dynamic Datasource只需要引入一个依赖就可以了
https://fastdep.louislivi.com/#/module/fastdep-datasource

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值