springboot 多数据源配置

1.引入相关pom文件

java 复制代码
  <!-- spring boot 启动 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>log4j-api</artifactId>
                    <groupId>org.apache.logging.log4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>log4j-to-slf4j</artifactId>
                    <groupId>org.apache.logging.log4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
 <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>


        <!-- druid 官方 starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.22</version>
        </dependency>

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>jsqlparser</artifactId>
                    <groupId>com.github.jsqlparser</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
        </dependency>

        <dependency>
            <groupId>com.github.yulichang</groupId>
            <artifactId>mybatis-plus-join</artifactId>
            <version>${mybatis-plus-join.version}</version>
        </dependency>


        <!-- mybatis的分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.mybatis</groupId>
                    <artifactId>mybatis</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
<!-- 测试框架 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <artifactId>junit</artifactId>
                    <groupId>junit</groupId>
                </exclusion>
            </exclusions>
        </dependency>

2.配置yml文件

java 复制代码
#配置
spring:
  jackson:
    default-property-inclusion: non_null
  cloud:
    nacos:
      discovery:
        server-addr: ${tc.nacos.server-addr}
        namespace: ${tc.nacos.namespace}
        enabled: true
        register-enabled: true
        ephemeral: true
  #分析型数据库doris
  datasource:
    dynamic:
      primary: db1
    db1:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/mb_data_blend?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
      username: test
      password: 123456
      driver-class-name:  com.mysql.cj.jdbc.Driver
    db2:
      jdbc-url: jdbc:mysql://127.0.0.1:3307/mbdb?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false
      username: test
      password: 123456
      driver-class-name:  com.mysql.cj.jdbc.Driver
    druid:
      initial-size: 5
      min-idle: 10
      max-active: 20
      max-wait: 60000

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    banner: false
    db-config:
      logic-delete-value: 1
      logic-not-delete-value: 0
      #logic-delete-field: isDeleted
  mapper-locations: mapper/db1mapper/*.xml,mapper/db2mapper/*.xml

3.创建不同数据源的配置文件

3.1启动类

java 复制代码
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableAsync;

import java.text.SimpleDateFormat;
import java.util.Date;


@Slf4j
@EnableCaching
@SpringBootApplication(scanBasePackages="com.tc.mb")
@EnableDiscoveryClient
@MapperScan("com.tc.mb.mapper")
@EnableAsync
public class MbDataBlendApplication {

    public static void main(String[] args) {
        SpringApplication.run(MbDataBlendApplication.class, args);
        log.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " mb-data-blend service server started!");

    }

}

3.2配置文件

java 复制代码
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
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.ApplicationContext;
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 javax.sql.DataSource;
import java.util.function.Consumer;

/**
 * @Author: LinJun
 * @Date: 2023/3/3 10:13
 * @Description:数据源1
 */
@Configuration
@MapperScan(basePackages="com.tc.mb.mapper.db1mapper",sqlSessionFactoryRef = "db1SqlSessionFactory")
public class Db1DataSourceConfig {

    static final String MAPPER_LOCATION = "classpath:/mapper/db1mapper/*.xml";

    private final ApplicationContext applicationContext;

    public Db1DataSourceConfig(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

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

    //主数据源 maindb
    @Primary
    @Bean("db1SqlSessionFactory")
    public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource, MybatisPlusInterceptor interceptor) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        sqlSessionFactory.setPlugins(interceptor);

        GlobalConfig globalConfig = GlobalConfigUtils.defaults();
        this.getBeanThen(MetaObjectHandler.class, globalConfig::setMetaObjectHandler);
        this.getBeanThen(ISqlInjector.class, globalConfig::setSqlInjector);
        this.getBeanThen(IdentifierGenerator.class, globalConfig::setIdentifierGenerator);
        sqlSessionFactory.setGlobalConfig(globalConfig);
        return sqlSessionFactory.getObject();
    }

    private <T> void getBeanThen(Class<T> clazz, Consumer<T> consumer) {
        if (applicationContext.getBeanNamesForType(clazz, false, false).length > 0) {
            consumer.accept(applicationContext.getBean(clazz));
        }
    }

    @Primary
    @Bean(name = "db1TransactionManager")
    public DataSourceTransactionManager ds1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "db1SqlSessionTemplate")
    public SqlSessionTemplate ds1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

另外一个配置类,只是替换所有的db1为db2即可

而且实体类文件夹目录以及xml文件夹目录要和配置里面对应好,其他的就可以根据mybatisplus自动生成代码来了,运行时就会动态的加载切换不同的数据库源

相关推荐
yuanbenshidiaos1 分钟前
c++---------数据类型
java·jvm·c++
向宇it5 分钟前
【从零开始入门unity游戏开发之——C#篇25】C#面向对象动态多态——virtual、override 和 base 关键字、抽象类和抽象方法
java·开发语言·unity·c#·游戏引擎
Lojarro19 分钟前
【Spring】Spring框架之-AOP
java·mysql·spring
莫名其妙小饼干21 分钟前
网上球鞋竞拍系统|Java|SSM|VUE| 前后端分离
java·开发语言·maven·mssql
isolusion33 分钟前
Springboot的创建方式
java·spring boot·后端
Yvemil71 小时前
《开启微服务之旅:Spring Boot Web开发举例》(一)
前端·spring boot·微服务
zjw_rp1 小时前
Spring-AOP
java·后端·spring·spring-aop
Oneforlove_twoforjob1 小时前
【Java基础面试题033】Java泛型的作用是什么?
java·开发语言
TodoCoder1 小时前
【编程思想】CopyOnWrite是如何解决高并发场景中的读写瓶颈?
java·后端·面试
向宇it2 小时前
【从零开始入门unity游戏开发之——C#篇24】C#面向对象继承——万物之父(object)、装箱和拆箱、sealed 密封类
java·开发语言·unity·c#·游戏引擎