溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么使用SpringBoot配置多數(shù)據(jù)源

發(fā)布時間:2022-04-11 14:00:56 來源:億速云 閱讀:233 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了怎么使用SpringBoot配置多數(shù)據(jù)源的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇怎么使用SpringBoot配置多數(shù)據(jù)源文章都會有所收獲,下面我們一起來看看吧。

1. 引入jar包

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.5.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.multi.datasource</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</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</artifactId>
        </dependency>

        <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>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.8</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.22</version>
        </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>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2. properties配置

分別準備兩個數(shù)據(jù)源

server.port=18888
mybatis.mapper-locations=classpath:mapper/*.xml

my1.datasource.url=jdbc:mysql://10.0.0.125:3306/wyl?autoReconnect=true
my1.datasource.driverClassName=com.mysql.cj.jdbc.Driver
my1.datasource.username=root
my1.datasource.password=123456

my2.datasource.url=jdbc:mysql://10.0.0.160:3306/wyl?autoReconnect=true
my2.datasource.driverClassName=com.mysql.cj.jdbc.Driver
my2.datasource.username=root
my2.datasource.password=123456

3. 分別配置兩個數(shù)據(jù)源

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

package com.multi.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = My1DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "my1SqlSessionFactory")
public class My1DataSourceConfig {

    static final String PACKAGE = "com.multi.datasource.dao.my1";
    static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    @Value("${my1.datasource.url}")
    private String url;

    @Value("${my1.datasource.username}")
    private String user;

    @Value("${my1.datasource.password}")
    private String password;

    @Value("${my1.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "my1DataSource")
    public DataSource my1DataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setMaxWait(Integer.MAX_VALUE);
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnReturn(true);
        dataSource.setTestWhileIdle(true);
        return dataSource;
    }

    @Bean(name = "my1TransactionManager")
    public DataSourceTransactionManager my1TransactionManager() {
        return new DataSourceTransactionManager(my1DataSource());
    }

    @Bean(name = "my1SqlSessionFactory")
    public SqlSessionFactory my1SqlSessionFactory(@Qualifier("my1DataSource") DataSource my1DataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(my1DataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(My1DataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

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

package com.multi.datasource.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = My1DataSourceConfig.PACKAGE, sqlSessionFactoryRef = "my1SqlSessionFactory")
public class My1DataSourceConfig {

    static final String PACKAGE = "com.multi.datasource.dao.my1";
    static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    @Value("${my1.datasource.url}")
    private String url;

    @Value("${my1.datasource.username}")
    private String user;

    @Value("${my1.datasource.password}")
    private String password;

    @Value("${my1.datasource.driverClassName}")
    private String driverClass;

    @Bean(name = "my1DataSource")
    public DataSource my1DataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setMaxWait(Integer.MAX_VALUE);
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnReturn(true);
        dataSource.setTestWhileIdle(true);
        return dataSource;
    }

    @Bean(name = "my1TransactionManager")
    public DataSourceTransactionManager my1TransactionManager() {
        return new DataSourceTransactionManager(my1DataSource());
    }

    @Bean(name = "my1SqlSessionFactory")
    public SqlSessionFactory my1SqlSessionFactory(@Qualifier("my1DataSource") DataSource my1DataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(my1DataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(My1DataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}

4. Dao目錄

為了區(qū)分兩個數(shù)據(jù)源,分別設(shè)置了不同的目錄

package com.multi.datasource.dao.my1;

import com.multi.datasource.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface Test1Mapper {
    
    UserEntity query();
    
}
package com.multi.datasource.dao.my2;

import com.multi.datasource.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface Test2Mapper {
    
    UserEntity query();
    
}

5. Entity

package com.multi.datasource.entity;

import lombok.Data;

@Data
public class UserEntity {

    private String userName;

}

6. Mapper文件

從my1數(shù)據(jù)源查詢

<?xml version="1.0" encoding="UTF-8"?>
        <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.multi.datasource.dao.my1.Test1Mapper">

<select id="query" resultType="com.multi.datasource.entity.UserEntity">
        select user_name as userName from t_user
    </select>

</mapper>

從my2數(shù)據(jù)源查詢

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.multi.datasource.dao.my2.Test2Mapper">
    
    <select id="query" resultType="com.multi.datasource.entity.UserEntity">
        select user_name as userName from t_user
    </select>
    
</mapper>

7. Controller測試

package com.multi.datasource.controller;

import com.multi.datasource.dao.my1.Test1Mapper;
import com.multi.datasource.dao.my2.Test2Mapper;
import com.multi.datasource.entity.UserEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class TestController {

    @Resource
    private Test1Mapper test1Mapper;

    @Resource
    private Test2Mapper test2Mapper;

    @RequestMapping("query")
    public void query() {
        UserEntity user1 = test1Mapper.query();
        System.out.println("my1 dataSource:" + user1);


        UserEntity user2 = test2Mapper.query();
        System.out.println("my2 dataSource:" + user2);
    }

}

兩個數(shù)據(jù)源,對應(yīng)的user_name分別是zhangsan和lisi

怎么使用SpringBoot配置多數(shù)據(jù)源

怎么使用SpringBoot配置多數(shù)據(jù)源

8. 結(jié)果驗證

訪問 http://localhost:18888/query,結(jié)果如下

怎么使用SpringBoot配置多數(shù)據(jù)源

關(guān)于“怎么使用SpringBoot配置多數(shù)據(jù)源”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“怎么使用SpringBoot配置多數(shù)據(jù)源”知識都有一定的了解,大家如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI