怎么在SpringBoot中配置多数据源

本篇文章为大家展示了怎么在SpringBoot中配置多数据源,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

多数据源配置

首先是配置文件

  • 这里采用yml配置文件,其他类型配置文件同理

  • 我配置了两个数据源,一个名字叫ds1数据源,一个名字叫ds2数据源,如果你想配置更多的数据源,继续加就行了

spring:
 # 数据源配置
 datasource:
  ds1: #数据源1
   driver-class-name: com.mysql.jdbc.Driver # mysql的驱动你可以配置别的关系型数据库
   url: jdbc:mysql://ip:3306/db1 #数据源地址
   username: root # 用户名
   password: root # 密码
  ds2: # 数据源2
   driver-class-name: com.mysql.jdbc.Driver # mysql的驱动你可以配置别的关系型数据库
   url: jdbc:mysql://ip:3307/db2#数据源地址
   username: root # 用户名
   password: root # 密码

多数据源配置

增加一个Springboot的配置类

/**
 * 多数据源配置
 */
@Configuration
public class DataSourceConfig {

  //主数据源配置 ds1数据源
  @Primary
  @Bean(name = "ds1DataSourceProperties")
  @ConfigurationProperties(prefix = "spring.datasource.ds1")
  public DataSourceProperties ds1DataSourceProperties() {
    return new DataSourceProperties();
  }

  //主数据源 ds1数据源
  @Primary
  @Bean(name = "ds1DataSource")
  public DataSource ds1DataSource(@Qualifier("ds1DataSourceProperties") DataSourceProperties dataSourceProperties) {
    return dataSourceProperties.initializeDataSourceBuilder().build();
  }

  //第二个ds2数据源配置
  @Bean(name = "ds2DataSourceProperties")
  @ConfigurationProperties(prefix = "spring.datasource.ds2")
  public DataSourceProperties ds2DataSourceProperties() {
    return new DataSourceProperties();
  }

  //第二个ds2数据源
  @Bean("ds2DataSource")
  public DataSource ds2DataSource(@Qualifier("ds2DataSourceProperties") DataSourceProperties dataSourceProperties) {
    return dataSourceProperties.initializeDataSourceBuilder().build();
  }
}

JdbcTemplate多数据源配置

增加一个Springboot配置类

/**
 * JdbcTemplate多数据源配置
 * 依赖于数据源配置
 *
 * @see DataSourceConfig
 */
@Configuration
public class JdbcTemplateDataSourceConfig {

  //JdbcTemplate主数据源ds1数据源
  @Primary
  @Bean(name = "ds1JdbcTemplate")
  public JdbcTemplate ds1JdbcTemplate(@Qualifier("ds1DataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
  }

  //JdbcTemplate第二个ds2数据源
  @Bean(name = "ds2JdbcTemplate")
  public JdbcTemplate ds2JdbcTemplate(@Qualifier("ds2DataSource") DataSource dataSource) {
    return new JdbcTemplate(dataSource);
  }
}

mybatis 多数据源配置

增加一个SpringBoot配置类

mybatis多数据源的原理是根据不同包,调用不同的数据源,你只需要把你的mapper.java和mapper.xml(我喜欢叫dao.java和dao.xml)写在某个package中,springboot自动帮你实现数据源切换
核心代码就这句

@MapperScan(basePackages ="com.web.ds2.**.dao", sqlSessionTemplateRef = "ds2SqlSessionTemplate")

用来指定包扫描指定sqlSessionTemplateRef
sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/web/ds2/**/*.xml"));
用来指定mapper.xml的路径

详细配置代码如下

/**
 * Mybatis主数据源ds1配置
 * 多数据源配置依赖数据源配置
 * @see DataSourceConfig
 */
@Configuration
@MapperScan(basePackages ="com.web.ds1.**.dao", sqlSessionTemplateRef = "ds1SqlSessionTemplate")
public class MybatisPlusConfig4ds1 {

  //主数据源 ds1数据源
  @Primary
  @Bean("ds1SqlSessionFactory")
  public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("ds1DataSource") DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
            getResources("classpath*:com/web/ds1/**/*.xml")); 
    return sqlSessionFactory.getObject();
  }

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

  @Primary
  @Bean(name = "ds1SqlSessionTemplate")
  public SqlSessionTemplate ds1SqlSessionTemplate(@Qualifier("ds1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}
/**
 * Mybatis 第二个ds2数据源配置
 * 多数据源配置依赖数据源配置
 * @see DataSourceConfig
 */
@Configuration
@MapperScan(basePackages ="com.web.ds2.**.dao", sqlSessionTemplateRef = "ds2SqlSessionTemplate")
public class MybatisPlusConfig4ds2 {

  //ds2数据源
  @Bean("ds2SqlSessionFactory")
  public SqlSessionFactory ds2SqlSessionFactory(@Qualifier("ds2DataSource") DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
        getResources("classpath*:com/web/ds2/**/*.xml"));
    return sqlSessionFactory.getObject();
  }

//事务支持
  @Bean(name = "ds2TransactionManager")
  public DataSourceTransactionManager ds2TransactionManager(@Qualifier("ds2DataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "ds2SqlSessionTemplate")
  public SqlSessionTemplate ds2SqlSessionTemplate(@Qualifier("ds2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}

mybatis-plus 多数据源配置

mybatis-plus是mybatis的增强版,只增加,不影响。也就是说使用mybatis-plus兼容原来所有的mybatis代码和配置。然后又做了很多增加和简化使用,具体看官网教程https://mybatis.plus/

相对于mybatis的多数据源配置就是改了下 SqlSessionFactory
核心代码就是修改mybatis为mybatis-plus,如下

  @Bean("ds2SqlSessionFactory")
  public SqlSessionFactory ds2SqlSessionFactory(@Qualifier("ds2DataSource") DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    MybatisConfiguration configuration = new MybatisConfiguration();
    configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
    configuration.setJdbcTypeForNull(JdbcType.NULL);
    sqlSessionFactory.setConfiguration(configuration);
    sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
        getResources("classpath*:com/web/ds2/**/*.xml"));
    sqlSessionFactory.setPlugins(new Interceptor[]{
        new PaginationInterceptor(),
        new PerformanceInterceptor()
//            .setFormat(true),
    });
    sqlSessionFactory.setGlobalConfig(new GlobalConfig().setBanner(false));
    return sqlSessionFactory.getObject();
  }

全部配置代码如下

/**
 * Mybatis-plus ds2数据源配置
 * 多数据源配置依赖数据源配置
 * @see DataSourceConfig
 */
@Configuration
@MapperScan(basePackages ="com.web.ds2.**.dao", sqlSessionTemplateRef = "ds2SqlSessionTemplate")
public class MybatisPlusConfig4ds2{

  //ds2数据源
  @Bean("ds2SqlSessionFactory")
  public SqlSessionFactory ds2SqlSessionFactory(@Qualifier("ds2DataSource") DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    MybatisConfiguration configuration = new MybatisConfiguration();
    configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
    configuration.setJdbcTypeForNull(JdbcType.NULL);
    sqlSessionFactory.setConfiguration(configuration);
    sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
        getResources("classpath*:com/web/ds2/**/*.xml"));
    sqlSessionFactory.setPlugins(new Interceptor[]{
        new PaginationInterceptor(),
        new PerformanceInterceptor()
//            .setFormat(true),
    });
    sqlSessionFactory.setGlobalConfig(new GlobalConfig().setBanner(false));
    return sqlSessionFactory.getObject();
  }

  @Bean(name = "ds2TransactionManager")
  public DataSourceTransactionManager ds2TransactionManager(@Qualifier("ds2DataSource") DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

  @Bean(name = "ds2SqlSessionTemplate")
  public SqlSessionTemplate ds2SqlSessionTemplate(@Qualifier("ds2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}
/**
 * Mybatis-plus 主数据源ds1配置
 * 多数据源配置依赖数据源配置
 * @see DataSourceConfig
 */
@Configuration
@MapperScan(basePackages ="com.web.ds1.**.dao", sqlSessionTemplateRef = "ds1SqlSessionTemplate")
public class MybatisPlusConfig4ds1 {

  //主数据源 ds1数据源
  @Primary
  @Bean("ds1SqlSessionFactory")
  public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("ds1DataSource") DataSource dataSource) throws Exception {
    MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();
    sqlSessionFactory.setDataSource(dataSource);
    MybatisConfiguration configuration = new MybatisConfiguration();
    configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
    configuration.setJdbcTypeForNull(JdbcType.NULL);
    sqlSessionFactory.setConfiguration(configuration);
    sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().
            getResources("classpath*:com/ds1/web/ds1/**/*.xml"));
    sqlSessionFactory.setPlugins(new Interceptor[]{
        new PaginationInterceptor(),
        new PerformanceInterceptor()
//            .setFormat(true),
    });
    sqlSessionFactory.setGlobalConfig(new GlobalConfig().setBanner(false));
    return sqlSessionFactory.getObject();
  }

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

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

上述内容就是怎么在SpringBoot中配置多数据源,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注本站行业资讯频道。

相关推荐:

Springboot如何查询MySQL DATE字段?

springboot日期查询mysql date字段时的问题 在使用springboot查询mysql date字段时,可能会遇到日期类型不匹配的问题。这是因为springboot接收时间时默认为timestamp类型,而mysql date字段是日期类型。 解决方案 解决方法是将前端传来的日期字符串直接转换成date类型,然后使用mybatis-plus进行查询。代码示例如下:// 后端参数接收...

springboot怎么集成shiro框架

要在Spring Boot项目中集成Apache Shiro框架,可以按照以下步骤进行操作: 添加依赖:在pom.xml文件中添加Shiro和Spring Boot Shiro相关的依赖。例如: <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring-boot...

SpringBoot CommandLine如何配置

SpringBoot CommandLine是一个用于构建命令行应用的工具。要配置SpringBoot CommandLine,可以按照以下步骤进行操作: 添加依赖:在项目的pom.xml文件中添加SpringBoot CommandLine的依赖。 <dependency> <groupId>org.springframework.boot</groupId>...

SpringBoot CommandLine的优势何在

Spring Boot CommandLine 的优势主要有以下几点: 简化开发流程:Spring Boot CommandLine 可以帮助开发者快速构建命令行应用程序,简化了配置和开发流程。开发者只需要关注业务逻辑的实现,而不需要花费大量的时间去配置项目。 集成了常用功能:Spring Boot CommandLine 提供了许多常用的功能和组件,例如参数解析、命令行选项、日志记录等,开发者可...

使用SpringBoot CommandLine需要注意什么

在使用Spring Boot CommandLine时,需要注意以下几点: 引入必要的依赖:在pom.xml文件中添加Spring Boot CommandLine的依赖,如spring-boot-starter,spring-boot-starter-web等。 创建主应用程序类:创建一个包含main方法的主应用程序类,并使用@SpringBootApplication注解标记它。 实现命令行应...

SpringBoot CommandLine可以做哪些事情

Spring Boot CommandLine 可以用于以下几个方面: 运行Spring Boot应用程序:使用CommandLine可以直接在命令行中启动Spring Boot应用程序,而不需要使用IDE或者构建工具。 执行自定义命令:通过CommandLine可以执行自定义命令,例如初始化数据库、调用外部API、生成报告等。 与操作系统交互:可以通过CommandLine与操作系统交互,执行系...

SpringBoot CommandLine怎样解析参数

SpringBoot应用程序可以通过CommandLineRunner接口来解析命令行参数。以下是一个简单的示例: 首先,创建一个CommandLineRunner接口的实现类,并实现run方法: import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @...

SpringBoot CommandLine与Shell脚本如何交互

要在SpringBoot应用中与Shell脚本交互,可以使用Java中的ProcessBuilder类来执行Shell命令,并通过标准输入输出流来与Shell脚本交互。 以下是一个简单的示例代码,演示了如何在SpringBoot应用中执行Shell脚本并与其交互: import java.io.BufferedReader; import java.io.IOException; import j...