欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot整合多數據源配置方式

 更新時間:2021年12月28日 11:50:58   作者:AizenSousuke  
這篇文章主要介紹了springboot整合多數據源配置,多數據源整合springboot+mybatis使用分包方式整合,springboot+druid+mybatisplus使用注解整合,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下

簡介

主要介紹兩種整合方式,分別是 springboot+mybatis 使用分包方式整合,和 springboot+druid+mybatisplus 使用注解方式整合。

一、表結構

在本地新建兩個數據庫,名稱分別為db1db2,新建一張user表,表結構如下:

SQL代碼:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `name` varchar(25) NOT NULL COMMENT '姓名',
  `age` int(2) DEFAULT NULL COMMENT '年齡',
  `sex` tinyint(1) NOT NULL DEFAULT '0' COMMENT '性別:0-男,1-女',
  `addr` varchar(100) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8

二、多數據源整合

1. springboot+mybatis使用分包方式整合

1.1 主要依賴包

  • spring-boot-starter-web
  • mybatis-spring-boot-starter
  • mysql-connector-java
  • lombok

pom.xml 文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>multipledatasource</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>multipledatasource</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>
   
    <dependencies>
        <!-- spring 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
         <!-- mysql 依賴 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

1.2 application.yml 配置文件

server:
  port: 8080 # 啟動端口
spring:
  datasource: 
    db1: # 數據源1
      jdbc-url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver
    db2: # 數據源2
      jdbc-url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver

注意事項

各個版本的 springboot 配置 datasource 時參數有所變化,例如低版本配置數據庫 url 時使用 url 屬性,高版本使用 jdbc-url 屬性,請注意區(qū)分。

1.3 建立連接數據源的配置文件

第一個配置文件

@Configuration
@MapperScan(basePackages = "com.example.multipledatasource.mapper.db1", sqlSessionFactoryRef = "db1SqlSessionFactory")
public class DataSourceConfig1 {

    @Primary // 表示這個數據源是默認數據源, 這個注解必須要加,因為不加的話spring將分不清楚那個為主數據源(默認數據源)
    @Bean("db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1") //讀取application.yml中的配置參數映射成為一個對象
    public DataSource getDb1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mapper的xml形式文件位置必須要配置,不然將報錯:no statement (這種錯誤也可能是mapper的xml中,namespace與項目的路徑不一致導致)
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db1/*.xml"));
        return bean.getObject();
    }

    @Primary
    @Bean("db1SqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

第二個配置文件

@Configuration
@MapperScan(basePackages = "com.example.multipledatasource.mapper.db2", sqlSessionFactoryRef = "db2SqlSessionFactory")
public class DataSourceConfig2 {

    @Bean("db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource getDb1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("db2SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db2/*.xml"));
        return bean.getObject();
    }

    @Bean("db2SqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

1.4 具體實現

項目結構如下:

注意事項

  • 在 service 層中根據不同的業(yè)務注入不同的 dao 層
  • 如果是主從復制- -讀寫分離:比如 db1 中負責增刪改,db2 中負責查詢。但是需要注意的是負責增刪改的數據庫必須是主庫(master)

2. springboot+druid+mybatisplus使用注解整合

2.1 主要依賴包

  • spring-boot-starter-web
  • mybatis-plus-boot-starter
  • dynamic-datasource-spring-boot-starter # 配置動態(tài)數據源
  • druid-spring-boot-starter # 阿里的數據庫連接池
  • mysql-connector-java
  • lombok

pom.xml 文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.1.9.RELEASE</version>
       <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.example</groupId>
   <artifactId>mutipledatasource2</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>mutipledatasource2</name>
   <description>Demo project for Spring Boot</description>

   <properties>
       <java.version>1.8</java.version>
   </properties>

   <dependencies>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
       <dependency>
           <groupId>com.baomidou</groupId>
           <artifactId>mybatis-plus-boot-starter</artifactId>
           <version>3.2.0</version>
       </dependency>
       <dependency>
           <groupId>com.baomidou</groupId>
           <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
           <version>2.5.6</version>
       </dependency>
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <scope>runtime</scope>
       </dependency>
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>druid-spring-boot-starter</artifactId>
           <version>1.1.20</version>
       </dependency>
       <dependency>
           <groupId>org.projectlombok</groupId>
           <artifactId>lombok</artifactId>
           <optional>true</optional>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
       </dependency>
   </dependencies>

   <build>
       <plugins>
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
           </plugin>
       </plugins>
   </build>

   <profiles>
       <profile>
           <id>local1</id>
           <properties>
               <profileActive>local1</profileActive>
           </properties>
           <activation>
               <activeByDefault>true</activeByDefault>
           </activation>
       </profile>
       <profile>
           <id>local2</id>
           <properties>
               <profileActive>local2</profileActive>
           </properties>
       </profile>
   </profiles>
</project>

2.2 application.yml 配置文件

server:
  port: 8080
spring:
  datasource:
    dynamic:
      primary: db1 # 配置默認數據庫
      datasource:
        db1: # 數據源1配置
          url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
          username: root
          password: root
          driver-class-name: com.mysql.cj.jdbc.Driver
        db2: # 數據源2配置
          url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT%2B8
          username: root
          password: root
          driver-class-name: com.mysql.cj.jdbc.Driver
      durid:
        initial-size: 1
        max-active: 20
        min-idle: 1
        max-wait: 60000
  autoconfigure:
    exclude:  com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 去除druid配置

DruidDataSourceAutoConfigure會注入一個DataSourceWrapper,其會在原生的spring.datasource下找 url, username, password 等。動態(tài)數據源 URL 等配置是在 dynamic 下,因此需要排除,否則會報錯。排除方式有兩種,一種是上述配置文件排除,還有一種可以在項目啟動類排除:

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}

2.3 給使用非默認數據源添加注解@DS

@DS 可以注解在方法上和類上,同時存在方法注解優(yōu)先于類上注解。
注解在 service 實現或 mapper 接口方法上,不要同時在 service 和 mapper 注解。

@DS("db2") 
public interface UserMapper extends BaseMapper<User> {
}

@Service
@DS("db2")
public class ModelServiceImpl extends ServiceImpl<ModelMapper, Model> implements IModelService {}

  @Select("SELECT * FROM user")
  @DS("db2")
  List<User> selectAll();

到此這篇關于springboot整合多數據源配置的文章就介紹到這了,更多相關springboot整合多數據源內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 文件路徑正確,報java.io.FileNotFoundException異常的原因及解決辦法

    文件路徑正確,報java.io.FileNotFoundException異常的原因及解決辦法

    這篇文章主要介紹了文件路徑正確,報java.io.FileNotFoundException異常的原因及解決辦法的相關資料,需要的朋友可以參考下
    2016-04-04
  • 解決IDEA中同項目引用報紅問題

    解決IDEA中同項目引用報紅問題

    在IDEA中,如果項目引用報紅,可能是因為IDEA的引用緩存問題,可以通過File->Invalidate Caches/Restart清空緩存并重建索引來解決,這個方法可以幫助解決同項目中引用找不到的問題,恢復正常的項目引用,消除報紅
    2024-09-09
  • Java實現高校教務系統(tǒng)

    Java實現高校教務系統(tǒng)

    這篇文章主要為大家詳細介紹了Java實現高校教務系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-08-08
  • Java圓柱體表面積和體積計算代碼實例

    Java圓柱體表面積和體積計算代碼實例

    這篇文章主要介紹了Java圓柱體表面積和體積計算代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • Java容器ArrayList知識點總結

    Java容器ArrayList知識點總結

    本篇文章給大家分享了Java容器ArrayList的相關知識點,對此有需要的朋友可以跟著學習參考下。
    2018-05-05
  • Spring?Security權限想要細化到按鈕實現示例

    Spring?Security權限想要細化到按鈕實現示例

    這篇文章主要為大家介紹了Spring?Security權限想要細化到按鈕實現示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-07-07
  • Springboot實現前后端分離excel下載

    Springboot實現前后端分離excel下載

    這篇文章主要介紹了Springboot實現前后端分離excel下載,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Spring AOP如何在注解上使用SPEL表達式注入對象

    Spring AOP如何在注解上使用SPEL表達式注入對象

    這篇文章主要介紹了Spring AOP如何在注解上使用SPEL表達式注入對象,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • 使用jdk1.8實現將list根據指定的值去分組的操作

    使用jdk1.8實現將list根據指定的值去分組的操作

    這篇文章主要介紹了使用jdk1.8實現將list根據指定的值去分組的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • Spring bean注冊到容器的總結

    Spring bean注冊到容器的總結

    這篇文章主要介紹了Spring bean注冊到容器的總結,本文給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2024-12-12

最新評論