springboot多数据源的使用

本质就是引入两套数据源,在不同的业务实现中,使用不同的数据库操作
1:引入pom依赖

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.14</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <!--解决No supported DataSource type found-->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.2.0</version>
        </dependency>
    </dependencies>
    
    <!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

2:配置文件配置多数据源
application.properties

## test1 database
spring.datasource.test1.jdbc-url=jdbc:mysql://127.0.0.1:3306/master?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.test1.username=root
spring.datasource.test1.password=123456
spring.datasource.test1.driver-class-name=com.mysql.jdbc.Driver

## test2 database
spring.datasource.test2.jdbc-url=jdbc:mysql://127.0.0.1:3306/slave?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.test2.username=root
spring.datasource.test2.password=123456
spring.datasource.test2.driver-class-name=com.mysql.jdbc.Driver

3:生成对应的配置类文件 MasterConfig(主)

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.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

//表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = "com.qingnian.orm.demo.dao.master", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterConfig {
    
    
    // 将这个对象放入Spring容器中
    @Bean(name = "masterDataSource")
    // 表示这个数据源是默认数据源
    @Primary
    // 读取application.properties中的配置参数映射成为一个对象
    // prefix表示参数的前缀
    @ConfigurationProperties(prefix = "spring.datasource.test1")
    public DataSource getDateSource1() {
    
    
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "masterSqlSessionFactory")
    // 表示这个数据源是默认数据源
    @Primary
    // @Qualifier表示查找Spring容器中名字为test1DataSource的对象
    public SqlSessionFactory test1SqlSessionFactory(@Qualifier("masterDataSource") DataSource datasource)
            throws Exception {
    
    
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                // 设置mybatis的xml所在位置
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/master/*.xml"));
        return bean.getObject();
    }

    @Bean("masterSqlSessionTemplate")
    // 表示这个数据源是默认数据源
    @Primary
    public SqlSessionTemplate test1sqlsessiontemplate(
            @Qualifier("masterSqlSessionFactory") SqlSessionFactory sessionfactory) {
    
    
        return new SqlSessionTemplate(sessionfactory);
    }
}

SlaveConfig(副)

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.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.qingnian.orm.demo.dao.slave", sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class SlaveConfig {
    
    

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

    @Bean(name = "slaveSqlSessionFactory")
    public SqlSessionFactory test2SqlSessionFactory(@Qualifier("slaveDataSource") DataSource datasource)
            throws Exception {
    
    
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(datasource);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/slave/*.xml"));
        return bean.getObject();
    }

    @Bean("slaveSqlSessionTemplate")
    public SqlSessionTemplate test2sqlsessiontemplate(
            @Qualifier("slaveSqlSessionFactory") SqlSessionFactory sessionfactory) {
    
    
        return new SqlSessionTemplate(sessionfactory);
    }
}

项目结构:
在这里插入图片描述
4:使用,定义两套xml,dao层接口类,在业务层注入不同的持久层对象,按需求使用即可

import com.qingnian.orm.demo.dao.master.StudentDao;
import com.qingnian.orm.demo.entity.Student;
import com.qingnian.orm.demo.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/*
任涛 -----专用
*/
@Service
@Slf4j
public class StudentServiceImpl implements StudentService {
    
    

    @Autowired
    @Qualifier("masterStudentDao")
    private StudentDao masterStuDao;

    @Autowired
    @Qualifier("slaveStudentDao")
    private com.qingnian.orm.demo.dao.slave.StudentDao slaveStuDao;

    @Override
    public Student getSlaveOne(Integer id) {
    
    
        log.info("slaveStuDao执行了getSlaveOne方法");
        return slaveStuDao.getOne(id);
    }

    @Override
    public Student getMasterOne(Integer id) {
    
    
        log.info("masterStuDao执行了getSlaveOne方法");
        return masterStuDao.getOne(id);
    }

    @Override
    public boolean getUnitAdd(Student student) {
    
    
        student.setName("master+slave");
        //联合新增
        Integer integer = masterStuDao.addOne(student);
        if(integer<1){
    
    
            //新增失败,抛出异常
            throw new RuntimeException("masterStuDao.addOne新增数据失败");
        }
        integer = slaveStuDao.addOne(student);
        if(integer<1){
    
    
            //新增失败,抛出异常
            throw new RuntimeException("slaveStuDao.addOne新增数据失败");
        }

        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44971379/article/details/108460531

相关文章