SpringBoot如何整合多個數(shù)據(jù)源?

SpringBoot現(xiàn)在是很多很多公司應用的后端框架,因為它搭建快,能更好、更快速的整合其他第三方。那么隨著業(yè)務的不斷擴展,業(yè)務量的增加,這時候就會牽扯到分庫分表,雖然這個詞聽起來很熟悉,作為程序員也很容易理解,但是我想應該也有不少讀者沒接觸過分庫分表,今天我們不聊如何分庫分表,而是聊SpringBoot如何整合多個數(shù)據(jù)源的事情。也就是如何接入不同的(多個)數(shù)據(jù)庫。

創(chuàng)新互聯(lián)公司主營章貢網(wǎng)站建設的網(wǎng)絡公司,主營網(wǎng)站建設方案,重慶APP開發(fā),章貢h5重慶小程序開發(fā)公司搭建,章貢網(wǎng)站營銷推廣歡迎章貢等地區(qū)企業(yè)咨詢

Spring Boot 如何整合多個數(shù)據(jù)源?

我們直接開始,我們直接創(chuàng)建一個干凈的SpringBoot應用。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>

<dependency>
    <groupId>MySQL</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.8</version>
</dependency>

引入需要的maven坐標,那么我們這個工程就算搭建起來了,接下來就是配置,如何讓SpringBoot整合兩個Mysql數(shù)據(jù)源。首先我們在本地創(chuàng)建兩個數(shù)據(jù)庫test1和test2,同時在里面創(chuàng)建兩個結構一樣的表。

CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用戶ID',
  `username` varchar(100) CHARACTER SET utf8 NOT NULL COMMENT '用戶名',
  `password` varchar(100) NOT NULL COMMENT '密碼',
  `create_time` datetime DEFAULT NULL COMMENT '創(chuàng)建時間',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

在我們的工程中配置application.yml文件,將數(shù)據(jù)庫的信息配置進去

spring:
  datasource:
    test1:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
      username: root
      password: 1234

    test2:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
      username: root
      password: 1234

接下來就是寫我們的配置類了,這也是整合多個數(shù)據(jù)源最為關鍵的部分。

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @ClassName DataSource2Config
 * @Description TODO
 * @Auther lbt
 * @Date 2019/6/28/028 10:07
 * @Version 1.0
 */
@Configuration
@MapperScan(basePackages = "com.example.mapper.test1", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config {

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

    @Bean(name = "test1SqlSessionFactory")
    @Primary
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean(name = "test1TransactionManager")
    @Primary
    public DataSourceTransactionManager test1TransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "test1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate test1SqlSessionTemplate(@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

第二個數(shù)據(jù)源的配置

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.example.mapper.test2", sqlSessionFactoryRef = "test2SqlSessionFactory")
public class DataSource2Config {

    @Bean(name = "test2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.test2")
    public DataSource test2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "test2SqlSessionFactory")
    public SqlSessionFactory test2SqlSessionFactory(@Qualifier("test2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    @Bean(name = "test2TransactionManager")
    public DataSourceTransactionManager test2TransactionManager(@Qualifier("test2DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "test2SqlSessionTemplate")
    public SqlSessionTemplate test2SqlSessionTemplate(@Qualifier("test2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

這樣我們整個的配置其實就算好了,我們接下來寫一個Controller類來測試一下,我們整合的數(shù)據(jù)源是不是真的可以用呢?

@RestController
public class TestController {

    @Autowired
    private User1Service user1Service;

    @Autowired
    private User2Service user2Service;

    @RequestMapping("/user1")
    public Object user1Controller() {

        List<UserPo> all = user1Service.findAll();

        return all;
    }

    @RequestMapping("/user2")
    public Object user2Controller() {

        List<UserPo> all = user2Service.findAll();

        return all;
    }
}

我寫了個兩個Controller方法,分別訪問不同的接口,我們來看下訪問結果。

當我們訪問user1的時候返回如下:

Spring Boot 如何整合多個數(shù)據(jù)源?

當我們訪問user2的時候訪問如下

Spring Boot 如何整合多個數(shù)據(jù)源?

看到這里其實我們的整個整合也就完成了, 雖然看起來很簡單,但是你如果沒寫過確實會走很多坑,我剛整合的時候就遇到了很多坑,為了幫助大家重復采坑,分享出來供大家參考.

當前名稱:SpringBoot如何整合多個數(shù)據(jù)源?
文章路徑:http://www.muchs.cn/article18/ijcggp.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設計公司用戶體驗、面包屑導航、網(wǎng)站建設網(wǎng)站維護、企業(yè)網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都app開發(fā)公司