Spring?Boot整合持久層之JdbcTemplate多數(shù)據(jù)源
多數(shù)據(jù)源
所謂多數(shù)據(jù)源,就是一個 Java EE 項(xiàng)目中采用了不同數(shù)據(jù)庫實(shí)例中的多個庫,或者同一個數(shù)據(jù)庫實(shí)例中多個不同的庫。一般來說,采用 MyCat 等分布式數(shù)據(jù)庫中間件是比較好的解決方案,這樣可以把數(shù)據(jù)庫讀寫分離、分庫分表、備份等操作交給中間件去做,Java 代碼只需要專注于業(yè)務(wù)即可。不過這并不意味著無法使用 Java 代碼解決類似的問題,在 Spring Framework 中就可以配置多數(shù)據(jù)源,Spring Boot 繼承其衣缽,只不過配置方式有所變化。
JdbcTemplate 多數(shù)據(jù)源
JdbcTemplate 多數(shù)據(jù)源是比較簡單的,因?yàn)橐粋€ JdbcTemplate 對應(yīng)一個 DataSource,開發(fā)者只需要手動提供多個 DataSource ,再手動配置 JdbcTemplate 即可。
1. 創(chuàng)建數(shù)據(jù)庫
創(chuàng)建兩個數(shù)據(jù)庫:chapter05-1 和 chapter05-2.兩個庫中都創(chuàng)建 book 表,再各預(yù)設(shè) 1 條數(shù)據(jù),腳本如下
create database `chapter05-1` default character set utf8; CREATE TABLE `chapter05-1`.`book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `author` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `chapter05-1`.`book`(`id`, `name`, `author`) VALUES (1, '水滸傳', '施耐庵'); create database `chapter05-2` default character set utf8; CREATE TABLE `chapter05-2`.`book` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `author` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `chapter05-2`.`book`(`id`, `name`, `author`) VALUES (1, '三國演義', '羅貫中');
2.創(chuàng)建項(xiàng)目
創(chuàng)建 Spring Boot Web 項(xiàng)目,添加如下依賴:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
注意這里添加的數(shù)據(jù)庫連接池依賴是 druid-spring-boot-starter 。druid-spring-boot-starter 可以幫助開發(fā)者在 Spring Boot 項(xiàng)目中輕松集成 Druid 數(shù)據(jù)庫連接池和監(jiān)控。
3. 配置數(shù)據(jù)庫連接
在application.properties 中配置數(shù)據(jù)庫連接信息
# 數(shù)據(jù)源1
spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.one.url=jdbc:mysql://localhost:3306/chapter05-1?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.one.username=root
spring.datasource.one.password=root
# 數(shù)據(jù)源2
spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.two.url=jdbc:mysql://localhost:3306/chapter05-2?useUnicode=true&characterEncoding=utf8&useSSL=true
spring.datasource.two.username=root
spring.datasource.two.password=root
4. 配置數(shù)據(jù)源
創(chuàng)建 DataSourceConfig 配置數(shù)據(jù)源,根據(jù) application.properties 中的配置生成兩個數(shù)據(jù)源
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.one")
DataSource dsOne() {
return DruidDataSourceBuilder.create().build();
}
@Bean
@ConfigurationProperties("spring.datasource.two")
DataSource dsTwo() {
return DruidDataSourceBuilder.create().build();
}
}
代碼解釋:
- DataSourceConfig 中提供了兩個數(shù)據(jù)源:dsOne 和 dsTwo,默認(rèn)方法名即實(shí)例名
- @ConfigurationProperties 注解表示使用不同前綴的配置文件來創(chuàng)建不同的 DataSource 實(shí)例
5. 配置 JdbcTemplate
在 5.1節(jié) 中得知,只要引入了 spring-jdbc 依賴,開發(fā)者沒有提供 JdbcTemplate 實(shí)例時,Spring Boot 默認(rèn)會提供一個 JdbcTemplate 實(shí)例?,F(xiàn)在配置多數(shù)據(jù)源時,由開發(fā)者自己提供 JdbcTemplate 實(shí)例
@Configuration
public class JdbcTemplateConfig {
@Bean
JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean
JdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}代碼解釋:
JdbcTemplateConfig 中提供兩個 JdbcTemplate 實(shí)例。每個 JdbcTemplate 實(shí)例都需要提供 DataSource,由于Spring 容器中有兩個 DataSource 實(shí)例,因此需要通過方法名查找。@Qualifier 注解表示查找不同名稱的 DataSource 實(shí)例注入進(jìn)來
6. 創(chuàng)建BookController
創(chuàng)建實(shí)體類 Book 和 BookController 進(jìn)行測試
public class Book {
private Integer id;
private String name;
private String author;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}@RestController
public class BookController {
@Resource(name = "jdbcTemplateOne")
JdbcTemplate jdbcTemplate;
@Autowired
@Qualifier("jdbcTemplateTwo")
JdbcTemplate jdbcTemplateTwo;
@GetMapping("/test1")
public void test1() {
List<Book> books1 = jdbcTemplate.query("select * from book",
new BeanPropertyRowMapper<>(Book.class));
List<Book> books2 = jdbcTemplateTwo.query("select * from book",
new BeanPropertyRowMapper<>(Book.class));
System.out.println("books1:"+books1);
System.out.println("books2:"+books2);
}
}簡單起見,這里沒有添加 service 層,而是直接將 JdbcTemplate 注入到了 Controller 中。在Controller 中注入兩個不同的 JdbcTemplate 有兩種方式:一種是使用 @Resource 注解,并指明 name 屬性,即按 name 進(jìn)行裝配,此時會根據(jù)實(shí)例名查找相應(yīng)的實(shí)例注入;另一種是使用 @Autowired 注解結(jié)合 @Qualifier 注解,效果等同于使用 @Resource 注解。
7. 測試
http://localhost:8081/test1,查看打印日志
books1:[Book{id=1, name='水滸傳', author='施耐庵'}]
books2:[Book{id=1, name='三國演義', author='羅貫中'}]
到此這篇關(guān)于Spring Boot整合持久層之JdbcTemplate多數(shù)據(jù)源的文章就介紹到這了,更多相關(guān)Spring Boot JdbcTemplate 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Spring Boot 整合持久層之JdbcTemplate
- SpringBoot2使用JTA組件實(shí)現(xiàn)基于JdbcTemplate多數(shù)據(jù)源事務(wù)管理(親測好用)
- 詳解SpringBoot中JdbcTemplate的事務(wù)控制
- 詳解Springboot之整合JDBCTemplate配置多數(shù)據(jù)源
- SpringBoot多數(shù)據(jù)源配置詳細(xì)教程(JdbcTemplate、mybatis)
- SpringBoot使用JdbcTemplate操作數(shù)據(jù)庫
- 詳解spring boot中使用JdbcTemplate
- Spring Boot中的JdbcTemplate是什么及用法小結(jié)
相關(guān)文章
Sentinel?Gateway自定義限流返回結(jié)果方式
這篇文章主要介紹了Sentinel?Gateway自定義限流返回結(jié)果方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
springboot的LogbackLoggingSystem配置加載流程解析
這篇文章主要介紹了springboot的LogbackLoggingSystem配置加載流程源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
Java集合中的fail-fast(快速失敗)機(jī)制詳解
這篇文章主要給大家介紹了關(guān)于Java集合中fail-fast(快速失敗)機(jī)制的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02
java擴(kuò)展Hibernate注解支持java8新時間類型
這篇文章主要介紹了java擴(kuò)展Hibernate注解支持java8新時間類型,需要的朋友可以參考下2014-04-04
Java實(shí)現(xiàn)整合文件上傳到FastDFS的方法詳細(xì)
FastDFS是一個開源的輕量級分布式文件系統(tǒng),對文件進(jìn)行管理,功能包括:文件存儲、文件同步、文件上傳、文件下載等,解決了大容量存儲和負(fù)載均衡的問題。本文將提供Java將文件上傳至FastDFS的示例代碼,需要的參考一下2022-02-02
Java項(xiàng)目Guava包?HashMultimap使用及注意事項(xiàng)
guava基本上可以說是java開發(fā)項(xiàng)目中,大概率會引入的包,今天介紹的主角是一個特殊的容器HashMultmap,可以簡單的將它的數(shù)據(jù)結(jié)構(gòu)理解為Map<K,?Set<V>>,今天主要介紹下基礎(chǔ)的知識點(diǎn)?HashMultmap級使用,感興趣的朋友一起看看吧2022-05-05

