springboot 多数据源配置

1.引入相关pom文件

  
        
            org.springframework.boot
            spring-boot-starter
            
                
                    log4j-api
                    org.apache.logging.log4j
                
                
                    log4j-to-slf4j
                    org.apache.logging.log4j
                
            
        
 
        
            mysql
            mysql-connector-java
        


        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.22
        

        
        
            com.baomidou
            mybatis-plus-boot-starter
        

        
            com.baomidou
            mybatis-plus
            
                
                    jsqlparser
                    com.github.jsqlparser
                
            
        

        
            com.baomidou
            mybatis-plus-generator
        

        
            com.github.yulichang
            mybatis-plus-join
            ${mybatis-plus-join.version}
        


        
        
            com.github.pagehelper
            pagehelper-spring-boot-starter
            
                
                    org.mybatis
                    mybatis
                
            
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    junit
                    junit
                
            
        

2.配置yml文件

#配置
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.创建不同数据源的配置文件

springboot 多数据源配置_第1张图片

 3.1启动类

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配置文件

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  void getBeanThen(Class clazz, Consumer 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自动生成代码来了,运行时就会动态的加载切换不同的数据库源

你可能感兴趣的:(spring,boot,后端,java)