相较于单数据源,双数据源配置有时候在数据分库的时候可能更加有利

但是在参考诸多博客以及书籍(汪云飞的实战书)的时候,发现对于spring boot1.X是完全没问题的,一旦切换到spring boot2.X的时候,就会报出无法实例化出数据源对象等各种问题。我猜测这是无法很好的读取到数据源配置信息的关系。

目前来说,官方文档示例比较好的解决了这个问题

配置双数据源

这里使用java配置方式,需要注意以下几点:

  • 主数据源要加上@Primary注解
  • 需要通过构建DataSourceProperties这个Bean来构建一个数据源,这也是官方文档的示例配置方式,如果采用1.X的方式,很可能会报出jdbcUrl is required with driverClassName这个错误,之后的DataSourceBean,EntityFactoryBean等都会无法实例化
@Configuration
public class DataSourceConfig {
@Bean
@Primary
@ConfigurationProperties("app.datasource.primary")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
} @Bean(name = "primaryDataSource")
@Primary
@ConfigurationProperties("app.datasource.primary")
public DataSource primaryDataSource() {
return firstDataSourceProperties().initializeDataSourceBuilder().build();
} @Bean
@ConfigurationProperties("app.datasource.secondary")
public DataSourceProperties secondDataSourceProperties() {
return new DataSourceProperties();
} @Bean(name = "secondaryDataSource")
@ConfigurationProperties("app.datasource.secondary")
public DataSource secondaryDataSource() {
return secondDataSourceProperties().initializeDataSourceBuilder().build();
}
}

配置yml文件

就是在application.yml文件里写一些数据库的配置信息,这个应该都比较轻车熟路了。关于是使用propertiesyml方式,看个人习惯

spring:
jpa:
show-sql: true
hibernate:
ddl-auto: update
app:
datasource:
primary:
url: jdbc:mysql://localhost:3306/kpimanage
username: root
password: root123
maximum-pool-size: 30
driver-class-name: com.mysql.jdbc.Driver
secondary:
url: jdbc:mysql://localhost:3306/local
username: root
password: root123
maximum-pool-size: 30
driver-class-name: com.mysql.jdbc.Driver

配置Spring Jpa

主要是以下几点:

  • 启动事务管理
  • 定义entity包。也可以不定义,使用默认扫描的方式
  • 定义repository包。也可以不定义,使用默认扫描的方式
  • 自定义EntiryManagerFactoryBean
  • 注意这里只是对使用spring data jpa来说有用,如果使用mybatis的话,根据自身情况配置,这里的配置完全不适用
@Configuration
@EnableTransactionManagement//开启事务管理
@EnableJpaRepositories(basePackages = "com.luzj.dblsource.repository.primary",
entityManagerFactoryRef = "entityManagerFactoryPrimary",
transactionManagerRef = "transactionManagerPrimary")//jpa 配置>repository位置,实体管理Factory配置,事务管理配置
public class PrimaryConfig { @Autowired @Qualifier("primaryDataSource")
DataSource primaryDataSource; // 自定义EntityManagerFactory
@Primary
@Bean(name = "entityManagerFactoryPrimary")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(primaryDataSource)
.packages("com.luzj.dblsource.entity.primary") //设置实体类所在位置
.persistenceUnit("primaryPersistenceUnit")
.build();
} //自定义EntityManager
@Primary
@Bean(name = "entityManagerPrimary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
} //自定义TransactionManager
@Primary
@Bean(name = "transactionManagerPrimary")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryPrimary(builder).getObject());
return transactionManager;
}
}

同时,第二数据源也如此配置

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.luzj.dblsource.repository.secondary",
entityManagerFactoryRef = "entityManagerFactorySecondary",
transactionManagerRef = "transactionManagerSecondary")
public class SecondaryConfig {
//...
}

测试

配置基本到此结束,下面分别在两个数据库建立不同的table,然后使用repository对表进行操作,看是否能够顺利运行

primary数据库建立Person表以及repository

@Entity
public class Person {
@Id
@GeneratedValue
private Integer id; private String address; private Integer age; private String name;
//setter getter...
}
public interface PersonRepository extends JpaRepository<Person,Integer> {
}

secondary数据库建立code_river表

@Entity
@Table(name = "code_river")
public class CodeRiver {
@Id
@Column(name = "river_id")
private String id; @Column(name = "river_desc")
private String riverDesc;
//setter getter ...
}
public interface CodeRiverRepository extends JpaRepository<CodeRiver,String> {
}

单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class DblsourceApplicationTests { @Test
public void contextLoads() {
}
@Autowired
private PersonRepository personRepository;
@Autowired
private CodeRiverRepository codeRiverRepository; @Test
public void test(){
personRepository.save(new Person("湖南",23,"章邯"));
personRepository.save(new Person("纽约",27,"john"));
personRepository.save(new Person("香港",43,"张一山"));
personRepository.save(new Person("北京",44,"张朝阳"));
personRepository.save(new Person("深圳",53,"马化腾")); Assert.assertEquals(5,personRepository.findAll().size()); codeRiverRepository.save(new CodeRiver("area110","阿姆斯特朗回旋加速过海"));
Assert.assertEquals(1,codeRiverRepository.findAll().size());
}
}

小结

主要介绍了在springboot 2.4环境下多数据源的配置方式

代码地址

参考

Spring Boot2.4双数据源的配置的更多相关文章

  1. Spring Boot2.x 动态数据源配置

    原文链接: Spring Boot2.x 动态数据源配置 基于 Spring Boot 2.x.Spring Data JPA.druid.mysql 的动态数据源配置Demo,适合用于数据库的读写分 ...

  2. Springboot spring data jpa 多数据源的配置01

    Springboot spring data jpa 多数据源的配置 (说明:这只是引入了多个数据源,他们各自管理各自的事务,并没有实现统一的事务控制) 例: user数据库   global 数据库 ...

  3. spring与mysql整合数据源的配置

    需要解决两点,数据源的配置交给spring完成,事务管理交个spring来管理. <context:property-placeholder location="classpath:c ...

  4. 【spring cloud】spring cloud2.X spring boot2.0.4调用feign配置Hystrix Dashboard 和 集成Turbine 【解决:Hystrix仪表盘Unable to connect to Command Metric Stream】【解决:Hystrix仪表盘Loading...】

    环境: <java.version>1.8</java.version><spring-boot.version>2.0.4.RELEASE</spring- ...

  5. Spring Boot2.0+中,自定义配置类扩展springMVC的功能

    在spring boot1.0+,我们可以使用WebMvcConfigurerAdapter来扩展springMVC的功能,其中自定义的拦截器并不会拦截静态资源(js.css等). @Configur ...

  6. Spring Boot,Spring Data JPA多数据源支持配置

    1 配置文件 wisely.primary.datasource.driverClassName=oracle.jdbc.OracleDriver wisely.primary.datasource. ...

  7. Spring全家桶--单数据源的配置

    前言 spring数据源的配置网络上有很多例子,这里我也来介绍一下单数据源配置的例子,基于SpringBoot的方式和原生的Spring的方式. 一.生成项目骨架(SpringBoot),运行一个简单 ...

  8. Spring Boot2.0之多环境配置

    本地开发环境 测试环境 实际项目中 区分不同的环境配置文件信息 首先创建三种不同场景下的配置文件: 内容分别是: ###dev http_url="dev" ###prdhttp_ ...

  9. Spring Boot2.2.X中Tomcat配置 错误定制

    1: Tomcat定制 EmbeddedServletContainerCustomizer 已久废弃 按照下面的方式来处理 通过的类的配置 @Component public class Tomca ...

随机推荐

  1. oracle学习篇一:sqlplus常用命令

    1.程序运行--> cmd --> sqlplus 登陆普通用户:scott/brant;普通管理员用户登陆:system/brant;高级管理员用户登陆:1>先切换其他用户:SQL ...

  2. 前端(三大框架、Bootstrap,jQuery,自整理)

    前端,HTML(超文本标记语言),CSS(层叠样式表)和JavaScript(脚本语言) HTML,通常说的h5,其实按标准来说,HTML4的后续版本不带编号了,并保证向前的兼容性 CSS的版本3,增 ...

  3. JS支持可变参数(任意多个)

    <script type="text/javascript"> function abc(){ //js中有个变量arguments,可以访问所有传入的值 for(va ...

  4. Facet constraits error: Spring 4.1 requires Java 1.6 or newer.

    问题来源: 在高版本的myeclipse,同步低版本的myeclipse提交的项目,可能会出现配置不一致. 问题描述: spring4.1不支持jdk1.6 注:在下载项目到本地的时候,myeclip ...

  5. Java程序员面试题集2

    51.类ExampleA 继承Exception,类ExampleB 继承ExampleA. 有如下代码片断: try{ throw new ExampleB("b") }catc ...

  6. bootstrap table 怎么实现前两列固定冻结?

    $("#Table").bootstrapTable('destroy').bootstrapTable({ pagination: true,//分页 minimumCountC ...

  7. 类型系统(type system)是一门编程语言最核心也是最基础的部分---编程语言最终的目标,本质上无非是回答两个问题:如何表示信息、如何处理信息

    https://www.cnblogs.com/feng9exe/p/9712059.html 类型系统(type system)是一门编程语言最核心也是最基础的部分.无论该语言基于何种编程范式,都必 ...

  8. 网络体系结构的概念 - 网络协议TCP - 红黑联盟

    https://i.cnblogs.com/EditPosts.aspx?opt=1 网络体系结构的概念  计算机网络就是一组通过一定形式连接起来的计算机系统,它需要四个要素的支持,即通信线路和通信设 ...

  9. IOS开发之——IOS模拟器调试蓝牙BLE

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/zhenyu5211314/article/details/24399887 因为在iPhone 4s ...

  10. Android NDK r8 Cygwin CDT 在window下开发环境搭建 安装配置与使用 具体图文解说

    版权声明:本博客全部文章均为原创.欢迎交流.欢迎转载:转载请勿篡改内容,而且注明出处,谢谢! https://blog.csdn.net/waldmer/article/details/3272500 ...