一文springboot自定义多数据源

前言:

自定义多数据源通常用于满足项目中对不同数据库进行访问的需求,特别是在与第三方系统对接时,可能需要直接连接第三方的数据库以获取或更新数据,这个时候就需要使用多数据源进行走不同的数据库查询数据,可以使用如Baomidou的Dynamic DataSource 多数据源,使用注解@DB进行切数据库;当然也可以自己自定义一个多数据源。下面进行演示:使用springboot+myabtis-plus+HikariCP+mysql+mariadb

一:准备工作

  • 1.mvn依赖
			 <!--web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
			<!--HikariCP 数据源-->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>
        <!--mariadb-->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
				<!--mybatis plus-->
 				<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-annotation</artifactId>
        </dependency>
  • 2.配置文件

application.ymlapplication.properties中配置数据源信息

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
		#第一个数据源,连接mysql
    first:
      driverClassName: com.mysql.cj.jdbc.Driver
      jdbcUrl: jdbc:mysql://127.0.0.1:3306/mysql-student?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
      username: root
      password: 123456
      type: ${spring.datasource.type}

		#第二个数据源,连接mariadb
    second:
      driverClassName: org.mariadb.jdbc.Driver
      jdbcUrl: jdbc:mariadb://192.168.160.128:3307/mariadb-student?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&autoReconnect=true&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true
      username: root
      password: 123456
      type: ${spring.datasource.type}

--- # mybatis-plus配置
mybatis-plus:
  global-config:
    dbConfig:
      idType: ASSIGN_ID    #id使用雪花算法

二:配置多数据源

  • 配置mysql数据源
//数据源配置类
@Configuration
//指定Mapper接口的位置
@MapperScan(basePackages = "com.study.mapper.first", 
            sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDataSourceConfiguration {

    //分页插件
    @Autowired
    private MybatisPlusInterceptor mybatisPlusInterceptor;

		 // 指定mapper xml文件路径
    public static final String MAPPER_LOCATION = "classpath*:mapper/first/*Mapper.xml";

		//全局自定义配置
    @Bean(name = "globalConfig")
    @ConfigurationProperties(prefix = "mybatis-plus")
    public GlobalConfig globalConfig() {
        return new GlobalConfig();
    }

		//mysql数据源信息:驱动类名、URL、用户名、密码
    @Primary
    @Bean("firstHikariConfig")
    @ConfigurationProperties(prefix = "spring.datasource.first")
    public HikariConfig firstHikariConfig() {
        return new HikariConfig();
    }

    @Primary
    @Bean("firstDataSource")
    public HikariDataSource firstDataSource(@Qualifier("firstHikariConfig") HikariConfig hikariConfig) {
        return new HikariDataSource(hikariConfig);
    }

    //配置事务管理器
    @Bean(name = "firstTransactionManager")
    @Primary
    public PlatformTransactionManager firstTransactionManager(@Qualifier("firstDataSource") HikariDataSource hikariDataSource) {
        return new DataSourceTransactionManager(hikariDataSource);
    }

    //自定义SQLSession工厂
    @Primary
    @Bean(name = "firstSqlSessionFactory")
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") HikariDataSource hikariDataSource,
                                                    @Qualifier("globalConfig") GlobalConfig globalConfig) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(hikariDataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        sessionFactoryBean.setGlobalConfig(globalConfig);
        sessionFactoryBean.setPlugins(mybatisPlusInterceptor);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        // 配置打印sql语句
        configuration.setLogImpl(StdOutImpl.class);
        sessionFactoryBean.setConfiguration(configuration);

        return sessionFactoryBean.getObject();
    }
	
    @Primary
    @Bean(name = "firstSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory firstSqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(firstSqlSessionFactory);
    }
}
  • 配置mariadb数据源
//数据源配置类
@Configuration
//指定Mapper接口的位置
@MapperScan(basePackages = "com.study.mapper.second", 
            sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfiguration {
	
  	//分页插件
    @Autowired
    private MybatisPlusInterceptor mybatisPlusInterceptor;
  
  	//指定mapper.xml文件路径
    public static final String MAPPER_LOCATION = "classpath*:mapper/second/*Mapper.xml";

		//mariadb数据源信息:驱动类名、URL、用户名、密码
    @Bean("secondHikariConfig")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public HikariConfig secondHikariConfig() {
        return new HikariConfig();
    }

		//HikariDataSource数据源
    @Bean("secondDataSource")
    public HikariDataSource secondDataSource(@Qualifier("secondHikariConfig") HikariConfig hikariConfig) {
        return new HikariDataSource(hikariConfig);
    }

   	//配置事务管理器
    @Bean(name = "secondTransactionManager")
    public PlatformTransactionManager secondTransactionManager(@Qualifier("secondDataSource") HikariDataSource hikariDataSource) {
        return new DataSourceTransactionManager(hikariDataSource);
    }

 	 //自定义SQLSession工厂
    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") HikariDataSource hikariDataSource) throws Exception {
        MybatisSqlSessionFactoryBean sessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(hikariDataSource);
        sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        sessionFactoryBean.setPlugins(mybatisPlusInterceptor);
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        // 配置打印sql语句
        configuration.setLogImpl(StdOutImpl.class);
        sessionFactoryBean.setConfiguration(configuration);
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "secondSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
  • 分页插件
@Configuration
public class MybatisPlusConfig {
  	 //分页插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.POSTGRE_SQL));
        return interceptor;
    }
}
  • 演示项目的结构


二:演示

  • 1. 数据库

mysql服务:mysql-student库 ->student表。

mariadb服务:mariadb-student库 ->student表。


  • 2.简单查询

演示需求:根据id查询数据

结果:

  • mysql:


  • mariadb


  • 3.分页查询
  • msql



  • mariadb


注意:实际项目中需要根据具体需求进行调整和优化。特别是事务管理部分,需要确保每个数据源都有对应的事务管理器,并在Service层正确指定使用哪个事务管理器。此外,还可以使用一些开源的多数据源管理框架来简化配置和使用过程,如Baomidou的Dynamic DataSource等。这些框架通常提供了更灵活和强大的多数据源管理能力,可以根据项目需求进行选择和使用。

原文链接:,转发请注明来源!