spring-boot-route(十)多數據源切換


前面我們已經介紹了三種方式來操作數據庫,在實際開發中,往往會出現一個服務連接多個數據庫的需求,這時候就需要在項目中進行靈活切換數據源來完成多個數據庫操作。這一章中,我們使用jdbcTemplate來學習多數據源的配置。

一 准備工作

1.1 建庫、建表

我們新建兩個庫db1db2,數據結構還是用前面演示的,分別在兩個庫中新建表student

CREATE TABLE `student` (
   `student_id` int(30) NOT NULL AUTO_INCREMENT,
   `age` int(1) DEFAULT NULL COMMENT '年齡',
   `name` varchar(45) DEFAULT NULL COMMENT '姓名',
   `sex` int(1) DEFAULT NULL COMMENT '性別:1:男,2:女,0:未知',
   `create_time` datetime DEFAULT NULL COMMENT '創建時間',
   `status` int(1) DEFAULT NULL COMMENT '狀態:1:正常,-1:刪除',
   PRIMARY KEY (`student_id`)
 ) ENGINE=InnoDB CHARSET=utf8mb4 CHECKSUM=1 DELAY_KEY_WRITE=1 ROW_FORMAT=DYNAMIC COMMENT='學生表'

1.2 引入mysql和jdbcTemplate依賴

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

1.3 寫入兩個數據源配置

spring:
  datasource:
    db1:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/db1
      username: root
      password: root
    db2:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/db2
      username: root
      password: root

二 多數據源配置

@Configuration
public class DataSourceConfig {

    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource db1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource db2DataSource(){
        return DataSourceBuilder.create().build();
    }
}
  • @Primary:表示主的,即出現多個bean的時候如果不指定具體的bean,則會采用這個
  • @bean:標注為一個bean,如果不指定name屬性,則會使用創建bean方法的名字做為bean的名字
  • @ConfigurationProperties:讀取配置文件

三 配置JdbcTemplate對象

@Configuration
public class DataSourceConfig {
    
    @Bean
    public JdbcTemplate db1JdbcTemplate(@Qualifier("db1DataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    @Primary
    @Bean
    public JdbcTemplate db2JdbcTemplate(@Qualifier("db2DataSource") DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
}
  • @Qualifier:bean類型相同后,指定使用的bean的name

四 測試類

4.1 測試@Primary屬性

不指定使用哪個JdbcTemplate對象時,會使用標注了@Primary屬性的對象

@SpringBootTest
class SpringBootDatasourceApplicationTests {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Test
    void testPrimary() {
        jdbcTemplate.update("insert into student(name,age) values(?,?)",new Object[]{"Java旅途",18});
    }
}

4.2 測試多數據源

@SpringBootTest
class SpringBootDatasourceApplicationTests {


    @Autowired
    private JdbcTemplate db1JdbcTemplate;
    @Autowired
    private JdbcTemplate db2JdbcTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Test
    void contextLoads() {

        db1JdbcTemplate.update("insert into student(name,age) values(?,?)",new Object[]{"Java旅途",18});
        db2JdbcTemplate.update("insert into student(name,age) values(?,?)",new Object[]{"Java旅途",18});
    }
    }
}

這里分享一道面試題:@Autowired 與@Resource有什么區別

@Autowired是Spring提供的,@Resource是JDK提供的;

@Autowired是根據bean的類型匹配的,@Resource是根據bean的name匹配的;

如果@Autowird想要根據name匹配應該怎么做呢?

  1. 配合@Qualifier注解指定bean的name
  2. 使用變量名稱作為bean的id,@Autowired如果匹配到多個符合條件的對象后,會自動根據變量名稱做為bean的id繼續匹配。我們在4.2中采用的就是這種方式。

本文示例代碼已上傳至github,點個star支持一下!

Spring Boot系列教程目錄

spring-boot-route(一)Controller接收參數的幾種方式

spring-boot-route(二)讀取配置文件的幾種方式

spring-boot-route(三)實現多文件上傳

spring-boot-route(四)全局異常處理

spring-boot-route(五)整合swagger生成接口文檔

spring-boot-route(六)整合JApiDocs生成接口文檔

spring-boot-route(七)整合jdbcTemplate操作數據庫

spring-boot-route(八)整合mybatis操作數據庫

spring-boot-route(九)整合JPA操作數據庫

spring-boot-route(十)多數據源切換

spring-boot-route(十一)數據庫配置信息加密

spring-boot-route(十二)整合redis做為緩存

spring-boot-route(十三)整合RabbitMQ

spring-boot-route(十四)整合Kafka

spring-boot-route(十五)整合RocketMQ

spring-boot-route(十六)使用logback生產日志文件

spring-boot-route(十七)使用aop記錄操作日志

spring-boot-route(十八)spring-boot-adtuator監控應用

spring-boot-route(十九)spring-boot-admin監控服務

spring-boot-route(二十)Spring Task實現簡單定時任務

spring-boot-route(二十一)quartz實現動態定時任務

spring-boot-route(二十二)實現郵件發送功能

spring-boot-route(二十三)開發微信公眾號

spring-boot-route(二十四)分布式session的一致性處理

spring-boot-route(二十五)兩行代碼實現國際化

spring-boot-route(二十六)整合webSocket

這個系列的文章都是工作中頻繁用到的知識,學完這個系列,應付日常開發綽綽有余。如果還想了解其他內容,掃面下方二維碼告訴我,我會進一步完善這個系列的文章!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM