前言

随着业务量增大,可能有些业务不是放在同一个数据库中,所以系统有需求使用多个数据库完成业务需求,我们需要配置多个数据源,从而进行操作不同数据库中数据。

正文

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:(二十四)多数据源配置与使用的更多相关文章

  1. Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控

    Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控 Spring Boot Actuator提供了对单个Spring Boot的监控,信息包含: ...

  2. spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法

    spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法 前言 本篇接着<spring boot / cloud ...

  3. 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 多数 ...

  4. spring boot + druid + mybatis + atomikos 多数据源配置 并支持分布式事务

    文章目录 一.综述 1.1 项目说明 1.2 项目结构 二.配置多数据源并支持分布式事务 2.1 导入基本依赖 2.2 在yml中配置多数据源信息 2.3 进行多数据源的配置 三.整合结果测试 3.1 ...

  5. spring boot(二十)使用spring-boot-admin对服务进行监控

    上一篇文章<springboot(十九):使用Spring Boot Actuator监控应用>介绍了Spring Boot Actuator的使用,Spring Boot Actuato ...

  6. (转)Spring Boot(二十):使用 spring-boot-admin 对 Spring Boot 服务进行监控

    http://www.ityouknow.com/springboot/2018/02/11/spring-boot-admin.html 上一篇文章<Spring Boot(十九):使用 Sp ...

  7. 学习Spring Boot:(四)应用日志

    前言 应用日志是一个系统非常重要的一部分,后来不管是开发还是线上,日志都起到至关重要的作用.这次使用的是 Logback 日志框架. 正文 Spring Boot在所有内部日志中使用Commons L ...

  8. Spring Boot (十四): 响应式编程以及 Spring Boot Webflux 快速入门

    1. 什么是响应式编程 在计算机中,响应式编程或反应式编程(英语:Reactive programming)是一种面向数据流和变化传播的编程范式.这意味着可以在编程语言中很方便地表达静态或动态的数据流 ...

  9. Android学习路线(二十四)ActionBar Fragment运用最佳实践

    转载请注明出处:http://blog.csdn.net/sweetvvck/article/details/38645297 通过前面的几篇博客.大家看到了Google是怎样解释action bar ...

  10. Spring Cloud(十四)Config 配置中心与客户端的使用与详细

    前言 在上一篇 文章 中我们直接用了本应在本文中配置的Config Server,对Config也有了一个基本的认识,即 Spring Cloud Config 是一种用来动态获取Git.SVN.本地 ...

随机推荐

  1. UVA10559&POJ1390 Blocks 区间DP

    题目传送门:http://poj.org/problem?id=1390 题意:给出一个长为$N$的串,可以每次消除颜色相同的一段并获得其长度平方的分数,求最大分数.数据组数$\leq 15$,$N ...

  2. Luogu P1494 [国家集训队]小Z的袜子

    比较简单的莫队题,主要是为了熟练板子. 先考虑固定区间时我们怎么计算,假设区间\([l,r]\)内颜色为\(i\)的袜子有\(cnt_i\)只,那么对于颜色\(i\)来说,凑齐一双的情况个数为: \( ...

  3. java jdk 配置

    1.配置 C:\Program Files\Java\jdk1.8.0_131\bin 路径 到环境变量 Path

  4. item 1:理解template类型的推导

    本文翻译自modern effective C++,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 一些用户对复杂的系统会忽略它怎么工作,怎么设计的,但是很高兴去知道它完成的一些事.通过这 ...

  5. Mybatis中 collection 和 association 的区别?

    public class A{ private B b1; private List<B> b2;} 在映射b1属性时用association标签,(一对一的关系) 映射b2时用colle ...

  6. Nginx+keepalived 双机热备(主主模式)

    之前已经介绍了Nginx+Keepalived双机热备的主从模式,今天在此基础上说下主主模式的配置. 由之前的配置信息可知:master机器(master-node):103.110.98.14/19 ...

  7. Redis常用操作-------Key(键)

    1.DEL key [key ...] 删除给定的一个或多个 key . 不存在的 key 会被忽略. 可用版本: >= 1.0.0 时间复杂度: O(N), N 为被删除的 key 的数量. ...

  8. 基于SSH框架开发的《高校大学生选课系统》的质量属性的实现

    基于SSH框架开发的<高校大学生选课系统>的质量属性的实现 对于可用性采取的是错误预防战术,即阻止错误演变为故障:在本系统主要体现在以下两个方面:(1)对于学生登录模块,由于初次登陆,学生 ...

  9. <构建之法>8,9,10章的读后感

    第八章 这一章主要讲的是需求分析,主要介绍在客户需求五花八门的情况下,软件团队如何才能准确而全面地找到这些需求. 第九章 问题:我们现在怎样培养才能成为一名合格的PM呢? 第十章 问题:如果典型用户吴 ...

  10. [福大软工] Z班——Beta现场答辩反馈

    Beta现场答辩 互评反馈 各组对于 麻瓜制造者 的评价与建议 队伍名 评价与建议 *** 功能继续完善,二手市场有闲鱼这条大鱼,要继续体现区域性的优势 *** web端的UI很好看,但安卓和web相 ...