自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Spring boot的Mybatis多數(shù)據(jù)源配置

運(yùn)維 數(shù)據(jù)庫(kù)運(yùn)維
最近在項(xiàng)目開(kāi)發(fā)中,需要為一個(gè)使用 MySQL 數(shù)據(jù)庫(kù)的 SpringBoot 項(xiàng)目,新添加一個(gè) PLSQL 數(shù)據(jù)庫(kù)數(shù)據(jù)源,那么就需要進(jìn)行 SpringBoot 的多數(shù)據(jù)源開(kāi)發(fā)。代碼很簡(jiǎn)單,下面是實(shí)現(xiàn)的過(guò)程。

 最近在項(xiàng)目開(kāi)發(fā)中,需要為一個(gè)使用 MySQL 數(shù)據(jù)庫(kù)的 SpringBoot 項(xiàng)目,新添加一個(gè) PLSQL 數(shù)據(jù)庫(kù)數(shù)據(jù)源,那么就需要進(jìn)行 SpringBoot 的多數(shù)據(jù)源開(kāi)發(fā)。代碼很簡(jiǎn)單,下面是實(shí)現(xiàn)的過(guò)程。

環(huán)境準(zhǔn)備

實(shí)驗(yàn)環(huán)境:

  • JDK 1.8
  • SpringBoot 2.4.1
  • Maven 3.6.3
  • MySQL 5.7

因?yàn)槲冶镜刂挥?MySQL 數(shù)據(jù)庫(kù),為了方便演示,我會(huì)在啟動(dòng)一個(gè)本地 MySQL,在 MySQL 創(chuàng)建兩個(gè)數(shù)據(jù)庫(kù),每個(gè)庫(kù)中均有一個(gè)表,以此進(jìn)行演示。

數(shù)據(jù)準(zhǔn)備

本地 MySQL 端口默認(rèn)不做改動(dòng),端口號(hào) 3306。

創(chuàng)建數(shù)據(jù)庫(kù) demo1,demo2。在 demo1 數(shù)據(jù)庫(kù)中創(chuàng)建表 book。

  1. -- create table 
  2. create table Book 
  3.     id          int auto_increment 
  4.         primary key
  5.     author      varchar(64)  not null comment '作者信息'
  6.     name        varchar(64)  not null comment '書(shū)籍名稱(chēng)'
  7.     price       decimal      not null comment '價(jià)格'
  8.     createTime  datetime     null comment '上架時(shí)間'
  9.     description varchar(128) null comment '書(shū)籍描述' 
  10. ); 
  11. -- insert data 
  12. INSERT INTO demo1.Book (id, author, name, price, createTime, description) VALUES (1, '金庸''笑傲江湖', 13, '2020-12-19 15:26:51''武俠小說(shuō)'); 
  13. INSERT INTO demo1.Book (id, author, name, price, createTime, description) VALUES (2, '羅貫中''三國(guó)演義', 14, '2020-12-19 15:28:36''歷史小說(shuō)'); 

 在 demo2 數(shù)據(jù)庫(kù)中創(chuàng)建表 user。

  1. -- create table 
  2. create table User 
  3.     id       int auto_increment 
  4.         primary key
  5.     name     varchar(32) null comment '用戶(hù)名稱(chēng)'
  6.     birthday date        null comment '出生日期' 
  7.     comment '用戶(hù)信息表'
  8. -- insert data 
  9. INSERT INTO demo2.User (id, name, birthday) VALUES (1, '金庸''1924-03-10'); 
  10. INSERT INTO demo2.User (id, name, birthday) VALUES (2, '羅貫中''1330-01-10'); 

 數(shù)據(jù)準(zhǔn)備完畢,表中都新增了兩條數(shù)據(jù)。

項(xiàng)目準(zhǔn)備

這里直接從 Spring 官方上初始化一個(gè)添加了 web、lombok、mybatis、mysql 依賴(lài)的 SpringBoot 項(xiàng)目。

  • 訪(fǎng)問(wèn)直接下載: https://start.spring.io/starter.zip?type=maven-project&language=java&bootVersion=2.4.1.RELEASE&baseDir=demo&groupId=com&artifactId=wdbyte&name=demo&description=Demo%20project%20for%20Spring%20Boot&packageName=com.wdbyte.demo&packaging=jar&javaVersion=1.8&dependencies=mybatis,lombok,web,mysql

如果你手上已經(jīng)有了一個(gè) SpringBoot 項(xiàng)目,既然你想改造成多數(shù)據(jù)源,那么你應(yīng)該已經(jīng)有了一個(gè)數(shù)據(jù)源了,如果新增的數(shù)據(jù)源數(shù)據(jù)庫(kù)和目前的一致,你可以直接使用你的項(xiàng)目進(jìn)行改造測(cè)試。

多數(shù)據(jù)源

SpringBoot 的多數(shù)據(jù)源開(kāi)發(fā)十分簡(jiǎn)單,如果多個(gè)數(shù)據(jù)源的數(shù)據(jù)庫(kù)相同,比如都是 MySQL,那么依賴(lài)是不需要任何改動(dòng)的,只需要進(jìn)行多數(shù)據(jù)源配置即可。

如果你新增的數(shù)據(jù)庫(kù)數(shù)據(jù)源和目前的數(shù)據(jù)庫(kù)不同,記得引入新數(shù)據(jù)庫(kù)的驅(qū)動(dòng)依賴(lài),比如 MySQL 和 PGSQL。

  1. <dependency> 
  2.     <groupId>mysql</groupId> 
  3.     <artifactId>mysql-connector-java</artifactId> 
  4.     <scope>runtime</scope> 
  5. </dependency> 
  6.  
  7. <dependency> 
  8.     <groupId>org.postgresql</groupId> 
  9.     <artifactId>postgresql</artifactId> 
  10.     <version>42.2.7</version> 
  11. </dependency> 

 連接配置

既然有多個(gè)數(shù)據(jù)源,因?yàn)閿?shù)據(jù)庫(kù)用戶(hù)名密碼可能不相同,所以是需要配置多個(gè)數(shù)據(jù)源信息的,直接在 properties/yml 中配置即可。這里要注意根據(jù)配置的屬性名進(jìn)行區(qū)分,同時(shí)因?yàn)閿?shù)據(jù)源要有一個(gè)默認(rèn)使用的數(shù)據(jù)源,最好在名稱(chēng)上有所區(qū)分(這里使用 primary 作為主數(shù)據(jù)源標(biāo)識(shí))。

  1. ########################## 主數(shù)據(jù)源 ################################## 
  2. spring.datasource.primary.jdbc-url=jdbc:mysql://127.0.0.1:3306/demo1?characterEncoding=utf-8&serverTimezone=GMT%2B8 
  3. spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver 
  4. spring.datasource.primary.username=root 
  5. spring.datasource.primary.password
  6.  
  7. ########################## 第二個(gè)數(shù)據(jù)源 ############################### 
  8. spring.datasource.datasource2.jdbc-url=jdbc:mysql://127.0.0.1:3306/demo2?characterEncoding=utf-8&serverTimezone=GMT%2B8 
  9. spring.datasource.datasource2.driver-class-name=com.mysql.jdbc.Driver 
  10. spring.datasource.datasource2.username=root 
  11. spring.datasource.datasource2.password
  12.  
  13. # mybatis 
  14. mybatis.mapper-locations=classpath:mapper/*.xml 
  15. mybatis.type-aliases-package=com.wdbyte.domain 

 注意,配置中的數(shù)據(jù)源連接 url 末尾使用的是 jdbc-url .

因?yàn)槭褂昧?Mybatis 框架,所以 Mybatis 框架的配置信息也是少不了的,指定掃描目錄mapper 下的 mapper xml 配置文件。

Mybatis 配置

如何編寫(xiě) Mybatis Mapper 或者如何使用工具生成 Mybatis Mapper 不是本文的重點(diǎn),如果你不知道可以參考 Mybatis 官方文檔或者我之前的文章。

鏈接一: 使用 Mybatis(自動(dòng)生成插件) 訪(fǎng)問(wèn)數(shù)據(jù)庫(kù)

鏈接二: 使用 Mybatis 集成 pagehelper 分頁(yè)插件和 mapper 插件

下面我已經(jīng)按照上面的兩個(gè)庫(kù)中的兩個(gè)表,Book 和 User 表分別編寫(xiě)相應(yīng)的 Mybatis 配置。

創(chuàng)建 BookMapper.xml 和 UserMapper.xml 放到配置文件配置的路徑 mapper 目錄下。創(chuàng)建 UserMapper 和 BookMapper 接口操作類(lèi)放在不同的目錄。這里注意 Mapper 接口要按數(shù)據(jù)源分開(kāi)放在不同的目錄中。后續(xù)好使用不同的數(shù)據(jù)源配置掃描不同的目錄,這樣就可以實(shí)現(xiàn)不同的 Mapper 使用不同的數(shù)據(jù)源配置。


Service 層沒(méi)有變化,這里 BookMapper 和 UserMapper 都有一個(gè) selectAll() 方法用于查詢(xún)測(cè)試。

多數(shù)據(jù)源配置

上面你應(yīng)該看到了,到目前為止和 Mybatis 單數(shù)據(jù)源寫(xiě)法唯一的區(qū)別就是 Mapper 接口使用不同的目錄分開(kāi)了,那么這個(gè)不同點(diǎn)一定會(huì)在數(shù)據(jù)源配置中體現(xiàn)。

主數(shù)據(jù)源

開(kāi)始配置兩個(gè)數(shù)據(jù)源信息,先配置主數(shù)據(jù)源,配置掃描的 MapperScan 目錄為com.wdbyte.mapper.primary

  1. /** 
  2.  * 主數(shù)據(jù)源配置 
  3.  * 
  4.  * @author niujinpeng 
  5.  * @website: https://www.wdbyte.com 
  6.  * @date 2020/12/19 
  7.  */ 
  8. @Configuration 
  9. @MapperScan(basePackages = {"com.wdbyte.mapper.primary"}, sqlSessionFactoryRef = "sqlSessionFactory"
  10. public class PrimaryDataSourceConfig { 
  11.  
  12.     @Bean(name = "dataSource"
  13.     @ConfigurationProperties(prefix = "spring.datasource.primary"
  14.     @Primary 
  15.     public DataSource dataSource() { 
  16.         return DataSourceBuilder.create().build(); 
  17.     } 
  18.  
  19.     @Bean(name = "sqlSessionFactory"
  20.     @Primary 
  21.     public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception { 
  22.         SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 
  23.         bean.setDataSource(dataSource); 
  24.         bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); 
  25.         return bean.getObject(); 
  26.     } 
  27.  
  28.     @Bean(name = "transactionManager"
  29.     @Primary 
  30.     public DataSourceTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) { 
  31.         return new DataSourceTransactionManager(dataSource); 
  32.     } 
  33.  
  34.     @Bean(name = "sqlSessionTemplate"
  35.     @Primary 
  36.     public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) { 
  37.         return new SqlSessionTemplate(sqlSessionFactory); 
  38.     } 

 和單數(shù)據(jù)源不同的是這里把

  1. dataSource 
  2. sqlSessionFactory 
  3. transactionManager 
  4. sqlSessionTemplate 

 都單獨(dú)進(jìn)行了配置,簡(jiǎn)單的 bean 創(chuàng)建,下面是用到的一些注解說(shuō)明。

  • @ConfigurationProperties(prefix = "spring.datasource.primary") :使用spring.datasource.primary 開(kāi)頭的配置。
  • @Primary :聲明這是一個(gè)主數(shù)據(jù)源(默認(rèn)數(shù)據(jù)源),多數(shù)據(jù)源配置時(shí) 必不可少 。
  • @Qualifier :顯式選擇傳入的 Bean。

第二個(gè)數(shù)據(jù)源

第二個(gè)數(shù)據(jù)源和主數(shù)據(jù)源唯一不同的只是 MapperScan 掃描路徑和創(chuàng)建的 Bean 名稱(chēng),同時(shí)沒(méi)有 @Primary 主數(shù)據(jù)源的注解。

  1. /** 
  2.  * 第二個(gè)數(shù)據(jù)源配置 
  3.  *  
  4.  * @author niujinpeng 
  5.  * @website: https://www.wdbyte.com 
  6.  * @date 2020/12/19 
  7.  */ 
  8. @Configuration 
  9. @MapperScan(basePackages = {"com.wdbyte.mapper.datasource2"}, sqlSessionFactoryRef = "sqlSessionFactory2"
  10. public class SecondDataSourceConfig { 
  11.  
  12.     @Bean(name = "dataSource2"
  13.     @ConfigurationProperties(prefix = "spring.datasource.datasource2"
  14.     public DataSource dataSource() { 
  15.         return DataSourceBuilder.create().build(); 
  16.     } 
  17.  
  18.     @Bean(name = "sqlSessionFactory2"
  19.     public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) throws Exception { 
  20.         SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); 
  21.         bean.setDataSource(dataSource); 
  22.         bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml")); 
  23.         return bean.getObject(); 
  24.     } 
  25.  
  26.     @Bean(name = "transactionManager2"
  27.     public DataSourceTransactionManager transactionManager(@Qualifier("dataSource2") DataSource dataSource) { 
  28.         return new DataSourceTransactionManager(dataSource); 
  29.     } 
  30.  
  31.     @Bean(name = "sqlSessionTemplate2"
  32.     public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) { 
  33.         return new SqlSessionTemplate(sqlSessionFactory); 
  34.     } 

 注意:因?yàn)橐呀?jīng)在兩個(gè)數(shù)據(jù)源中分別配置了掃描的 Mapper 路徑,如果你之前在 SpringBoot 啟動(dòng)類(lèi)中也使用了 Mapper 掃描注解, 需要?jiǎng)h掉 。

訪(fǎng)問(wèn)測(cè)試

編寫(xiě)兩個(gè)簡(jiǎn)單的查詢(xún) Controller 然后進(jìn)行訪(fǎng)問(wèn)測(cè)試。

  1. // BookController 
  2. @RestController 
  3. public class BookController { 
  4.  
  5.     @Autowired 
  6.     private BookService bookService; 
  7.  
  8.     @GetMapping(value = "/books"
  9.     public Response selectAll() throws Exception { 
  10.         List<Book> books = bookService.selectAll(); 
  11.         return ResponseUtill.success(books); 
  12.     } 
  13.  
  14. // UserController 
  15. @RestController 
  16. public class UserController { 
  17.  
  18.     @Autowired 
  19.     private UserService userService; 
  20.  
  21.     @ResponseBody 
  22.     @GetMapping(value = "/users"
  23.     public Response selectAll() { 
  24.         List<User> userList = userService.selectAll(); 
  25.         return ResponseUtill.success(userList); 
  26.     } 

 訪(fǎng)問(wèn)測(cè)試,我這里直接 CURL 請(qǐng)求 

  1. ➜  ~ curl localhost:8080/books  
  2.   "code""0000"
  3.   "message""success"
  4.   "data": [ 
  5.     { 
  6.       "id": 1, 
  7.       "author""金庸"
  8.       "name""笑傲江湖"
  9.       "price": 13, 
  10.       "createtime""2020-12-19T07:26:51.000+00:00"
  11.       "description""武俠小說(shuō)" 
  12.     }, 
  13.     { 
  14.       "id": 2, 
  15.       "author""羅貫中"
  16.       "name""三國(guó)演義"
  17.       "price": 14, 
  18.       "createtime""2020-12-19T07:28:36.000+00:00"
  19.       "description""歷史小說(shuō)" 
  20.     } 
  21.   ] 
  22. ➜  ~ curl localhost:8080/users  
  23.   "code""0000"
  24.   "message""success"
  25.   "data": [ 
  26.     { 
  27.       "id": 1, 
  28.       "name""金庸"
  29.       "birthday""1924-03-09T16:00:00.000+00:00" 
  30.     }, 
  31.     { 
  32.       "id": 2, 
  33.       "name""羅貫中"
  34.       "birthday""1330-01-09T16:00:00.000+00:00" 
  35.     } 
  36.   ] 
  37. ➜  ~ 

 至此,多數(shù)據(jù)源配置完成,測(cè)試成功。

連接池

其實(shí)在多數(shù)據(jù)源改造中,我們一般情況下都不會(huì)使用默認(rèn)的 JDBC 連接方式,往往都需要引入連接池進(jìn)行連接優(yōu)化,不然你可能會(huì)經(jīng)常遇到數(shù)據(jù)源連接被斷開(kāi)等報(bào)錯(cuò)日志。其實(shí)數(shù)據(jù)源切換連接池?cái)?shù)據(jù)源也是十分簡(jiǎn)單的,直接引入連接池依賴(lài),然后把創(chuàng)建 dataSource 的部分換成連接池?cái)?shù)據(jù)源創(chuàng)建即可。

下面以阿里的 Druid 為例,先引入連接池?cái)?shù)據(jù)源依賴(lài)。

  1. <dependency> 
  2.    <groupId>com.alibaba</groupId> 
  3.    <artifactId>druid</artifactId> 
  4. </dependency> 

 添加 Druid 的一些配置。

  1. spring.datasource.datasource2.initialSize=3 # 根據(jù)自己情況設(shè)置 
  2. spring.datasource.datasource2.minIdle=3 
  3. spring.datasource.datasource2.maxActive=20 

 改寫(xiě) dataSource Bean 的創(chuàng)建代碼部分。

  1. @Value("${spring.datasource.datasource2.jdbc-url}"
  2. private String url; 
  3. @Value("${spring.datasource.datasource2.driver-class-name}"
  4. private String driverClassName; 
  5. @Value("${spring.datasource.datasource2.username}"
  6. private String username; 
  7. @Value("${spring.datasource.datasource2.password}"
  8. private String password
  9. @Value("${spring.datasource.datasource2.initialSize}"
  10. private int initialSize; 
  11. @Value("${spring.datasource.datasource2.minIdle}"
  12. private int minIdle; 
  13. @Value("${spring.datasource.datasource2.maxActive}"
  14. private int maxActive; 
  15.  
  16. @Bean(name = "dataSource2"
  17. public DataSource dataSource() { 
  18.     DruidDataSource dataSource = new DruidDataSource(); 
  19.     dataSource.setUrl(url); 
  20.     dataSource.setDriverClassName(driverClassName); 
  21.     dataSource.setUsername(username); 
  22.     dataSource.setPassword(password); 
  23.     dataSource.setInitialSize(initialSize); 
  24.     dataSource.setMinIdle(minIdle); 
  25.     dataSource.setMaxActive(maxActive); 
  26.     return dataSource; 

 【編輯推薦】

 

責(zé)任編輯:姜華 來(lái)源: 今日頭條
相關(guān)推薦

2022-05-18 12:04:19

Mybatis數(shù)據(jù)源Spring

2023-01-04 09:33:31

SpringBootMybatis

2024-10-30 10:22:17

2023-06-07 08:08:37

MybatisSpringBoot

2023-09-07 08:39:39

copy屬性數(shù)據(jù)源

2023-10-18 15:25:29

數(shù)據(jù)源數(shù)據(jù)庫(kù)

2009-08-14 10:26:27

ibatis多數(shù)據(jù)源

2020-11-24 09:56:12

數(shù)據(jù)源讀寫(xiě)分離

2022-06-02 10:38:42

微服務(wù)數(shù)據(jù)源分布式

2022-12-19 07:21:35

Hutool-db數(shù)據(jù)庫(kù)JDBC

2025-01-17 09:11:51

2023-12-13 12:20:36

SpringMySQL數(shù)據(jù)源

2023-10-31 07:52:53

多數(shù)據(jù)源管理后端

2010-12-27 09:59:11

ODBC數(shù)據(jù)源

2009-06-15 13:24:46

JBoss數(shù)據(jù)源

2023-01-10 16:30:22

Spring數(shù)據(jù)庫(kù)

2020-03-13 14:05:14

SpringBoot+數(shù)據(jù)源Java

2020-06-02 07:55:31

SpringBoot多數(shù)據(jù)源

2025-01-09 11:21:25

2022-05-10 10:43:35

數(shù)據(jù)源動(dòng)態(tài)切換Spring
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)