前言

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

正文

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. sql语句——行列互换

    SELECT 年份, SUM(case when 季度=1 then 销量 else 0 end) as 一季度, SUM(case when 季度=2 then 销量 else 0 end) as ...

  2. 使用 cron 定时任务实现 war 自动化发布

    autoRelease.sh #!/bin/sh /home/tomcat/bin/shutdown.sh echo "tomcat stoped" cd /home/tomcat ...

  3. iOS开发简记(2):自定义tabbar

    tabbar是放在APP底部的控件.常见的APP都使用tabbar来进行功能分类的管理,比如微信.QQ等等. 小程需要一个特殊一点的tabbar,要求突显中间的那个按钮,让中间按钮特别显眼,从而引导用 ...

  4. item 5: 比起显式的类型声明,更偏爱auto

    本文翻译自modern effective C++,由于水平有限,故无法保证翻译完全正确,欢迎指出错误.谢谢! 博客已经迁移到这里啦 啊,简单愉快的代码: int x; 等等,讨厌!我忘了初始化x,所 ...

  5. SQL多表查询总结

    前言 连接查询包括合并.内连接.外连接和交叉连接,如果涉及多表查询,了解这些连接的特点很重要.只有真正了解它们之间的区别,才能正确使用. 一.Union UNION 操作符用于合并两个或多个 SELE ...

  6. Spring Cloud :断路器集群监控(Turbine)

    一. 简介      上一篇文章我们已经实现了对单个服务实例的监控,当然在实际应用中,单个实例的监控数据没有多大的价值,我们更需要的是一个集群系统的监控信息,这时我们就需要引入Turbine.Turb ...

  7. 期末总结:LINUX内核分析与设计期末总结

    朱国庆原创作品转载请注明出处<Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 一,心得体会 关于网上听课这 ...

  8. Linux内核第五节 20135332武西垚

    20135332武西垚 在MenuOS中通过添加代码增加自定义的系统调用命令 使用gdb跟踪调试内核 简单分析system_call代码了解系统调用在内核代码中的处理过程 由于本周实验是在Kali虚拟 ...

  9. 第三个spring冲刺第3天

    基本功能跟界面都完成了,今天小组开了个会,基于跟别的小组对比的效果,感觉自己组的效果没别人的好,很多方面还欠缺,所以我们会继续跟进完善.

  10. C#-ToString格式化

    Int.ToString(format): 格式字符串采用以下形式:Axx,其中 A 为格式说明符,指定格式化类型,xx 为精度说明符,控制格式化输出的有效位数或小数位数,具体如下: 格式说明符 说明 ...