偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

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

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

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

環(huán)境準備

實驗環(huán)境:

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

因為我本地只有 MySQL 數(shù)據(jù)庫,為了方便演示,我會在啟動一個本地 MySQL,在 MySQL 創(chuàng)建兩個數(shù)據(jù)庫,每個庫中均有一個表,以此進行演示。

數(shù)據(jù)準備

本地 MySQL 端口默認不做改動,端口號 3306。

創(chuàng)建數(shù)據(jù)庫 demo1,demo2。在 demo1 數(shù)據(jù)庫中創(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 '書籍名稱'
  7.     price       decimal      not null comment '價格'
  8.     createTime  datetime     null comment '上架時間'
  9.     description varchar(128) null comment '書籍描述' 
  10. ); 
  11. -- insert data 
  12. INSERT INTO demo1.Book (id, author, name, price, createTime, description) VALUES (1, '金庸''笑傲江湖', 13, '2020-12-19 15:26:51''武俠小說'); 
  13. INSERT INTO demo1.Book (id, author, name, price, createTime, description) VALUES (2, '羅貫中''三國演義', 14, '2020-12-19 15:28:36''歷史小說'); 

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

  1. -- create table 
  2. create table User 
  3.     id       int auto_increment 
  4.         primary key
  5.     name     varchar(32) null comment '用戶名稱'
  6.     birthday date        null comment '出生日期' 
  7.     comment '用戶信息表'
  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ù)準備完畢,表中都新增了兩條數(shù)據(jù)。

項目準備

這里直接從 Spring 官方上初始化一個添加了 web、lombok、mybatis、mysql 依賴的 SpringBoot 項目。

  • 訪問直接下載: 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)有了一個 SpringBoot 項目,既然你想改造成多數(shù)據(jù)源,那么你應該已經(jīng)有了一個數(shù)據(jù)源了,如果新增的數(shù)據(jù)源數(shù)據(jù)庫和目前的一致,你可以直接使用你的項目進行改造測試。

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

SpringBoot 的多數(shù)據(jù)源開發(fā)十分簡單,如果多個數(shù)據(jù)源的數(shù)據(jù)庫相同,比如都是 MySQL,那么依賴是不需要任何改動的,只需要進行多數(shù)據(jù)源配置即可。

如果你新增的數(shù)據(jù)庫數(shù)據(jù)源和目前的數(shù)據(jù)庫不同,記得引入新數(shù)據(jù)庫的驅(qū)動依賴,比如 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> 

 連接配置

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

  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. ########################## 第二個數(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 .

因為使用了 Mybatis 框架,所以 Mybatis 框架的配置信息也是少不了的,指定掃描目錄mapper 下的 mapper xml 配置文件。

Mybatis 配置

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

鏈接一: 使用 Mybatis(自動生成插件) 訪問數(shù)據(jù)庫

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

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

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


Service 層沒有變化,這里 BookMapper 和 UserMapper 都有一個 selectAll() 方法用于查詢測試。

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

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

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

開始配置兩個數(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 

 都單獨進行了配置,簡單的 bean 創(chuàng)建,下面是用到的一些注解說明。

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

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

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

  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.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.     } 

 注意:因為已經(jīng)在兩個數(shù)據(jù)源中分別配置了掃描的 Mapper 路徑,如果你之前在 SpringBoot 啟動類中也使用了 Mapper 掃描注解, 需要刪掉 。

訪問測試

編寫兩個簡單的查詢 Controller 然后進行訪問測試。

  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.     } 

 訪問測試,我這里直接 CURL 請求 。

  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""武俠小說" 
  12.     }, 
  13.     { 
  14.       "id": 2, 
  15.       "author""羅貫中"
  16.       "name""三國演義"
  17.       "price": 14, 
  18.       "createtime""2020-12-19T07:28:36.000+00:00"
  19.       "description""歷史小說" 
  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ù)源配置完成,測試成功。

連接池

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

下面以阿里的 Druid 為例,先引入連接池數(shù)據(jù)源依賴。

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

 添加 Druid 的一些配置。

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

 改寫 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; 

 【編輯推薦】

 

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

2023-01-04 09:33:31

SpringBootMybatis

2022-05-18 12:04:19

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

2024-10-30 10:22:17

2023-06-07 08:08:37

MybatisSpringBoot

2023-09-07 08:39:39

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

2020-11-24 09:56:12

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

2009-08-14 10:26:27

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

2023-10-18 15:25:29

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

2022-12-19 07:21:35

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

2022-06-02 10:38:42

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

2025-01-17 09:11:51

2009-06-15 13:24:46

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

2010-12-27 09:59:11

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

2023-10-31 07:52:53

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

2023-12-13 12:20:36

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

2023-01-10 16:30:22

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

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ù)源動態(tài)切換Spring
點贊
收藏

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