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

但是在参考诸多博客以及书籍(汪云飞的实战书)的时候,发现对于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. cf567E. President and Roads(最短路计数)

    题意 题目链接 给出一张有向图,以及起点终点,判断每条边的状态: 是否一定在最短路上,是的话输出'YES' 如果不在最短路上,最少减去多少权值会使其在最短路上,如果减去后的权值\(< 1\),输 ...

  2. HTML表格相关元素

    <table> 标签定义 HTML 表格.简单的 HTML 表格由 table 元素以及一个或多个 tr.th 或 td 元素组成.tr 元素定义表格行,th 元素定义表头,td 元素定义 ...

  3. css样式学习小知识

    1. 使用百分比设置宽高 自适用宽高的,有分割的区域,可以适用百分比:30% 70% 如果有一部分是固定的宽度或者高度,可以使用:height: calc( 100% - 36px ); 2. inp ...

  4. C#中.Net的值传递和引用传递

    /// <summary> /// 电脑类 /// </summary> public class Computer { public string Type { get; s ...

  5. ArcGIS Enterprise 10.5.1 静默安装部署记录(Centos 7.2 minimal)- 1、安装前准备

    安装前准备 上传文件到服务器,x-ftp   xshell登陆Centos 检查机器名 修改机器名为:portal.cloud.local   方法一:零时设置,重启后失效,该方法不可取     方法 ...

  6. supervisor运行virtualenv环境下的nagios-api

    supervisord-example.conf [unix_http_server] file=/tmp/supervisor.sock ; path to your socket file [su ...

  7. MySQL登录之socket与TCP

    在一台测试服务器上部署了2个实例,一个端口是默认的3306,另一个端口是3376.MySQL的版本是5.6.35 [root@MySQL56_L1 ~]# ps -ef | grep mysql | ...

  8. rac环境修改除vip外的其他ip地址方法

    官方参考文档(metalink):如何修改集群的公网信息(包括 VIP) (文档 ID 1674442.1) 同事在测试环境测试通过,使用如下方法.如果有疑问,请参照上述文档,写的很详细.1.停止相关 ...

  9. CSS z-index的用法

    理清 position及z-index的用法: static :  无特殊定位,对象遵循HTML定位规则absolute :  将对象从文档流中拖出,使用left,right,top,bottom等属 ...

  10. 小于12px的字体大小在Chrome中不起作用

    今天遇见一个小问题,让人挺郁闷的,在Chrome浏览器中无法把字体变成12px以下.网上搜索以下,发现无论中文英文数字在网页中CSS设置小于12px后各大浏览器均支持,在谷歌chrome浏览器不支持解 ...