Springboot、Mybatis 实现多数据源配置

1、导入依赖 + yml 配置

导入Maven 依赖(其他依赖就不粘贴了,不想拉长篇幅)


            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            2.0.1
        


            mysql
            mysql-connector-java
            8.0.18
        

yml 配置

spring:
  datasource:
    order:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/transact-order?useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: root
      password: root
    orderlog:
      driver-class-name: com.mysql.cj.jdbc.Driver
      jdbc-url: jdbc:mysql://127.0.0.1:3306/transact-order-log?useUnicode=true&characterEncoding=UTF-8&useSSL=false
      username: root
      password: root

mybatis:
  mapper-locations: classpath:mapper/**/*.xml

2、增加多数据源代码配置

这才是最关键的

数据源 1 配置

package org.dawn.wheel.transact.order.configure;

import org.apache.ibatis.annotations.Mapper;
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.Autowired;
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 org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author yue
 * @since 2022-04-18
 **/

@Configuration
@MapperScan(basePackages = {"org.dawn.wheel.transact.order.ordermapper"}, sqlSessionFactoryRef = "orderSqlSessionFactory")
public class OrderDBConfigure {

    @Bean(name = "orderDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.order")
    @Primary
    public DataSource orderLogDateSource() throws SQLException {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "orderSqlSessionFactory")
    @Primary// 这个注解表示这个数据源是默认数据源,只能存在一个默认数据源。不然会报错
    public SqlSessionFactory orderSqlSessionFactory(@Qualifier("orderDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/order/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("orderSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("orderSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }

//    @Bean(name = "orderTransactionManager")
//    public PlatformTransactionManager transactionManager(@Qualifier("orderDataSource") DataSource dataSource) {
//        return new DataSourceTransactionManager(dataSource);
//    }
}

数据源 2 配置

package org.dawn.wheel.transact.order.configure;

import org.apache.ibatis.annotations.Mapper;
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.Autowired;
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 org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @author yue
 * @since 2022-04-18
 **/

@Configuration
@MapperScan(basePackages = {"org.dawn.wheel.transact.order.logmapper"},sqlSessionFactoryRef = "orderlogSqlSessionFactory")
public class OrderDBLogConfigure {

    @Bean(name = "orderlogDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.orderlog")
    public DataSource orderDataSource() throws SQLException {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "orderlogSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("orderlogDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/orderlog/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("orderlogSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("orderlogSqlSessionFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }


//    @Bean(name = "orderlogTransactionManager")
//    public PlatformTransactionManager transactionManager(@Qualifier("orderlogDataSource") DataSource dataSource) {
//        return new DataSourceTransactionManager(dataSource);
//    }

}

总结、测试

从上面的配置可以看出来,这种配置方法是基于 mapper 包来进行区分的,不同mapper包对应不同的数据源。
重点:如果是多数据源,那么久需要考虑业务,有没有在一个方法中使用多个数据源对数据进行修改来决定是否需要处理分布式事务(跨库事务)
基于上面的案例,处理分布式事务,可参考这个案例:https://www.jianshu.com/p/24b73b702202
看一下多数据源的整体结构吧

多数据源结构.png

你可能感兴趣的:(Springboot、Mybatis 实现多数据源配置)