学习Spring Boot:(二十四)多数据源配置与使用
前言
随着业务量增大,可能有些业务不是放在同一个数据库中,所以系统有需求使用多个数据库完成业务需求,我们需要配置多个数据源,从而进行操作不同数据库中数据。
正文
JdbcTemplate 多数据源
配置
需要在 Spring Boot 中配置多个数据库连接,当然怎么设置连接参数的 key 可以自己决定,
需要注意的是
Spring Boot 2.0的默认连接池配置参数好像有点问题,由于默认连接池已从Tomcat更改为HikariCP,以前有一个参数url,已经改成hikari.jdbcUrl,不然无法注册。我下面使用的版本是1.5.9。
server:
port: 8022
spring:
datasource:
url: jdbc:mysql://localhost:3306/learn?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
second-datasource:
url: jdbc:mysql://localhost:3306/learn1?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: 123457
driver-class-name: com.mysql.jdbc.Driver
注册 DataSource
注册两个数据源,分别注册两个 JdbcTemplate,
@Configuration
public class DataSourceConfig {
/**
* 注册 data source
*
* @return
*/
@ConfigurationProperties(prefix = "spring.datasource")
@Bean("firstDataSource")
@Primary // 有相同实例优先选择
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@ConfigurationProperties(prefix = "spring.second-datasource")
@Bean("secondDataSource")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean("firstJdbcTemplate")
@Primary
public JdbcTemplate firstJdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean("secondJdbcTemplate")
public JdbcTemplate secondJdbcTemplate(@Qualifier("secondDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestJDBC {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("secondJdbcTemplate")
private JdbcTemplate jdbcTemplate1;
@Before
public void before() {
jdbcTemplate.update("DELETE FROM employee");
jdbcTemplate1.update("DELETE FROM employee");
}
@Test
public void testJDBC() {
jdbcTemplate.update("insert into employee(id,name,age) VALUES (1, 'wuwii', 24)");
jdbcTemplate1.update("insert into employee(id,name,age) VALUES (1, 'kronchan', 23)");
Assert.assertThat("wuwii", Matchers.equalTo(jdbcTemplate.queryForObject("SELECT name FROM employee WHERE id=1", String.class)));
Assert.assertThat("kronchan", Matchers.equalTo(jdbcTemplate1.queryForObject("SELECT name FROM employee WHERE id=1", String.class)));
}
}
使用 JPA 支持多数据源
配置
相比使用 jdbcTemplate,需要设置下 JPA 的相关参数即可,没多大变化:
server:
port: 8022
spring:
datasource:
url: jdbc:mysql://localhost:3306/learn?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
second-datasource:
url: jdbc:mysql://localhost:3306/learn1?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
jpa:
show-sql: true
database: mysql
hibernate:
# update 更新表结构
# create 每次启动删除上次表,再创建表,会造成数据丢失
# create-drop: 每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
# validate :每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.MySQLDialect
首先一样的是我们要注册相应的 DataSource,还需要指定相应的数据源所对应的实体类和数据操作层 Repository的位置:
* firstDataSource
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "firstEntityManagerFactory",
transactionManagerRef = "firstTransactionManager",
basePackages = "com.wuwii.module.system.dao" // 设置该数据源对应 dao 层所在的位置
)
public class FirstDataSourceConfig {
@Autowired
private JpaProperties jpaProperties;
@Primary
@Bean(name = "firstEntityManager")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@ConfigurationProperties(prefix = "spring.datasource")
@Bean("firstDataSource")
@Primary // 有相同实例优先选择,相同实例只能设置唯一
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "firstEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(firstDataSource())
.properties(getVendorProperties(firstDataSource()))
.packages("com.wuwii.module.system.entity") //设置该数据源对应的实体类所在位置
.persistenceUnit("firstPersistenceUnit")
.build();
}
private Map<String, String> getVendorProperties(DataSource dataSource) {
return jpaProperties.getHibernateProperties(dataSource);
}
@Primary
@Bean(name = "firstTransactionManager")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
secondDataSource:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "secondEntityManagerFactory",
transactionManagerRef = "secondTransactionManager",
basePackages = "com.wuwii.module.user.dao" // 设置该数据源 dao 层所在的位置
)
public class SecondDataSourceConfig {
@Autowired
private JpaProperties jpaProperties;
@Bean(name = "secondEntityManager")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactoryPrimary(builder).getObject().createEntityManager();
}
@ConfigurationProperties(prefix = "spring.second-datasource")
@Bean("secondDataSource")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondDataSource())
.properties(getVendorProperties(secondDataSource()))
.packages("com.wuwii.module.user.entity") //设置该数据源锁对应的实体类所在的位置
.persistenceUnit("secondPersistenceUnit")
.build();
}
private Map<String, String> getVendorProperties(DataSource dataSource) {
return jpaProperties.getHibernateProperties(dataSource);
}
@Bean(name = "secondTransactionManager")
public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());
}
}
测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestDemo {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private UserDao userDao;
@Before
public void before() {
employeeDao.deleteAll();
userDao.deleteAll();
}
@Test
public void test() {
Employee employee = new Employee(null, "wuwii", 24);
employeeDao.save(employee);
User user = new User(null, "KronChan", 24);
userDao.save(user);
Assert.assertThat(employee, Matchers.equalTo(employeeDao.findOne(Example.of(employee))));
Assert.assertThat(user, Matchers.equalTo(userDao.findOne(Example.of(user))));
}
}
学习Spring Boot:(二十四)多数据源配置与使用的更多相关文章
- Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控
Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控 Spring Boot Actuator提供了对单个Spring Boot的监控,信息包含: ...
- spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法
spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法 前言 本篇接着<spring boot / cloud ...
- Spring Boot 2.x Redis多数据源配置(jedis,lettuce)
Spring Boot 2.x Redis多数据源配置(jedis,lettuce) 96 不敢预言的预言家 0.1 2018.11.13 14:22* 字数 65 阅读 727评论 0喜欢 2 多数 ...
- spring boot + druid + mybatis + atomikos 多数据源配置 并支持分布式事务
文章目录 一.综述 1.1 项目说明 1.2 项目结构 二.配置多数据源并支持分布式事务 2.1 导入基本依赖 2.2 在yml中配置多数据源信息 2.3 进行多数据源的配置 三.整合结果测试 3.1 ...
- spring boot(二十)使用spring-boot-admin对服务进行监控
上一篇文章<springboot(十九):使用Spring Boot Actuator监控应用>介绍了Spring Boot Actuator的使用,Spring Boot Actuato ...
- (转)Spring Boot(二十):使用 spring-boot-admin 对 Spring Boot 服务进行监控
http://www.ityouknow.com/springboot/2018/02/11/spring-boot-admin.html 上一篇文章<Spring Boot(十九):使用 Sp ...
- 学习Spring Boot:(四)应用日志
前言 应用日志是一个系统非常重要的一部分,后来不管是开发还是线上,日志都起到至关重要的作用.这次使用的是 Logback 日志框架. 正文 Spring Boot在所有内部日志中使用Commons L ...
- Spring Boot (十四): 响应式编程以及 Spring Boot Webflux 快速入门
1. 什么是响应式编程 在计算机中,响应式编程或反应式编程(英语:Reactive programming)是一种面向数据流和变化传播的编程范式.这意味着可以在编程语言中很方便地表达静态或动态的数据流 ...
- Android学习路线(二十四)ActionBar Fragment运用最佳实践
转载请注明出处:http://blog.csdn.net/sweetvvck/article/details/38645297 通过前面的几篇博客.大家看到了Google是怎样解释action bar ...
- Spring Cloud(十四)Config 配置中心与客户端的使用与详细
前言 在上一篇 文章 中我们直接用了本应在本文中配置的Config Server,对Config也有了一个基本的认识,即 Spring Cloud Config 是一种用来动态获取Git.SVN.本地 ...
随机推荐
- 实现Repeater控件的记录单选(二)
前一篇<实现Repeater控件的记录单选>http://www.cnblogs.com/insus/p/7426334.html 虽然可以实现对Repeater控件的记录进行单选,但是, ...
- 在VS2017上使用C#调用非托管C++生成的DLL文件(图文讲解)
原文:在VS2010上使用C#调用非托管C++生成的DLL文件(图文讲解) 背景 在项目过程中,有时候你需要调用非C#编写的DLL文件,尤其在使用一些第三方通讯组件的时候,通过C#来开发应用软件时,就 ...
- SQL跨服务器查询数据库
有时候一个项目需要用到两个数据库或多个数据库而且这些数据库在不同的服务器上时,就需要通过跨服务器查找数据 在A服务器的数据库a查询服务器B的数据库b 的bb表 假如服务器B的IP地址为:10.0.22 ...
- @media响应式的屏幕适配
当页面小于960px的时候执行 @media screen and (max-width: 960px){ body{ background: #000; } } 等于960px尺寸的代码 @medi ...
- [Oracle]ORA-600[kdBlkCheckError]LOB坏块处理
[Oracle]ORA-600[kdBlkCheckError]LOB坏块处理 客户环境报如下错误: ORA - 00600: Internal error code, arguments: [kdB ...
- C#一些常用的图片操作方法:生成文字图片 合并图片等
生成文字图片: /// <summary> /// 生成文字图片 /// </summary> /// <param name="text">& ...
- Roslyn入门(一)-C#语法分析
演示环境 Visual Studio 2017 .NET Compiler Platform SDK 简介 今天,Visual Basic和C#编译器是黑盒子:输入文本然后输出字节,编译管道的中间阶段 ...
- Ubuntu16.04下安装QQ的完整操作记录(经验证可用)
本机安装了Ubuntu16.04系统,用于日常运维办公.打算在Ubuntu上安装QQ,如下操作记录也使用于Ubuntu18.04: 1)先下载特制的QQ程序包(其实就是基于Wine容器做了一些封装,程 ...
- centos7下/etc/rc.local文件里配置的开机启动项不执行的解决办法
习惯于在/etc/rc.local文件里配置我们需要开机启动的服务,这个在centos6系统下是正常生效的.但是到了centos7系统下,发现/etc/rc.local文件里的开机启动项不执行了!仔细 ...
- bootstrap完善按钮组bug
.btn.active { border: 1px solid #ff9400 !important; color: #ff9400 !important; } <div class=" ...