在 MyBatis-Plus 中配置多数据源可以通过以下步骤实现:

  1. pom.xml 文件中添加相应的依赖:
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis-plus.version}</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>${druid.version}</version>
</dependency>
  1. application.properties 中配置数据库信息:
# 数据源1
spring.datasource.druid.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver

# 数据源2
spring.datasource.druid.slave.url=jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.druid.slave.username=root
spring.datasource.druid.slave.password=root
spring.datasource.druid.slave.driver-class-name=com.mysql.jdbc.Driver
  1. 在配置类中添加多数据源配置:
@Configuration
public class DataSourceConfig {

    @Bean
    @ConfigurationProperties('spring.datasource.druid')
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    @Bean
    @ConfigurationProperties('spring.datasource.druid.slave')
    public DataSource slaveDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public DataSource dynamicDataSource() {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put('dataSource', dataSource());
        targetDataSources.put('slaveDataSource', slaveDataSource());
        dynamicDataSource.setTargetDataSources(targetDataSources);
        dynamicDataSource.setDefaultTargetDataSource(dataSource());
        return dynamicDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        return sqlSessionFactoryBean.getObject();
    }

}
  1. DynamicDataSource 类中实现动态数据源切换:
public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return DbContextHolder.getDbType();
    }

}
  1. DbContextHolder 类中实现数据源切换:
public class DbContextHolder {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void setDbType(String dbType) {
        contextHolder.set(dbType);
    }

    public static String getDbType() {
        return contextHolder.get();
    }

    public static void clearDbType() {
        contextHolder.remove();
    }

}
  1. 在需要使用不同数据源的地方通过 DbContextHolder.setDbType('dataSource') 或者 DbContextHolder.setDbType('slaveDataSource') 来切换数据源。

通过以上步骤,就可以在 MyBatis-Plus 中实现多数据源配置。


原文地址: https://www.cveoy.top/t/topic/nGpU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录