Springboot配置双数据源

Springboot配置双数据源

数据库相关信息:
Springboot配置双数据源_第1张图片
Springboot配置双数据源_第2张图片
yml相关配置(单数据源与双数据源进行对比):

# 数据源配置(Mysql)
spring:
  datasource:
    # 单数据源(需要删除双数据源相关配置文件,注意是url)
#    url: jdbc:mysql://localhost:3306/standard?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&autoReconnect=true
#    driver-class-name: com.mysql.cj.jdbc.Driver  # 如果驱动类报红,将pom.xml中的mysql依赖的scope节点删除即可。
#    username: root
#    password: root
    # 双数据源
    database1:  # 数据源1(standard 数据库,注意是jdbc-url)
      jdbc-url: jdbc:mysql://localhost:3306/standard?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&autoReconnect=true
      driver-class-name: com.mysql.cj.jdbc.Driver  # 如果驱动类报红,将pom.xml中的mysql依赖的scope节点删除即可。
      username: root
      password: root
    database2:  # 数据源2(startplan 数据库,注意是jdbc-url)
      jdbc-url: jdbc:mysql://localhost:3306/startplan?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&autoReconnect=true
      driver-class-name: com.mysql.cj.jdbc.Driver  # 如果驱动类报红,将pom.xml中的mysql依赖的scope节点删除即可。
      username: root
      password: root
      
# Mybatis配置(单数据源需要配置,双数据源的时候不需要配置)
#mybatis:
#  type-aliases-package: com.kd.opt.entity      # 注意:对应实体类的路径
#  mapper-locations: classpath:mapper/*.xml    # 注意:一定要对应mapper映射xml文件的所在路径

双数据源相关配置文件:
Springboot配置双数据源_第3张图片
Springboot配置双数据源_第4张图片
Springboot配置双数据源_第5张图片

package com.kd.opt.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.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;

/**
 * 数据源1相关配置(作为主数据库,项目启动默认连接此数据库)
 *
 * 主数据库都有 @Primary注解,从数据库都没有
 *
 * 需要额外注意的位置
 * 1:扫描Dao层包路径,basePackages = "com.kd.opt.dao"
 * 2:关联yml中的数据源,@ConfigurationProperties(prefix = "spring.datasource.database1")
 * 3:扫描相关xml文件的所在路径,"classpath:mapper/*.xml"
 *
 * @author 小辰哥哥
 */
@Configuration
@MapperScan(basePackages = "com.kd.opt.dao", sqlSessionTemplateRef = "sqlSessionTemplate1")
public class DatabaseConfig1 {
    @Bean(name = "dataSource1")
    @ConfigurationProperties(prefix = "spring.datasource.database1")
    @Primary
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sqlSessionFactory1")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "transactionManager1")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource1") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionTemplate1")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
package com.kd.opt.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
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.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 数据源2相关配置(作为从数据库)
 *
 * 主数据库都有 @Primary注解,从数据库都没有
 *
 * 需要额外注意的位置
 * 1:扫描Dao层包路径,basePackages = "com.kd.opt.dao2"
 * 2:关联yml中的数据源,@ConfigurationProperties(prefix = "spring.datasource.database2")
 * 3:扫描相关xml文件的所在路径,"classpath:mapper2/*.xml"
 *
 * @author zhouziyu
 */
@Configuration
@MapperScan(basePackages = "com.kd.opt.dao2", sqlSessionTemplateRef = "sqlSessionTemplate2")
public class DatabaseConfig2 {
    @Bean(name = "dataSource2")
    @ConfigurationProperties(prefix = "spring.datasource.database2")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "sqlSessionFactory2")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper2/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "transactionManager2")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSource2") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "sqlSessionTemplate2")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

进行单元测试:

@Test
public void method() {

   // 主数据库,数据源1(standard)
   List<Standard> standards = standardMapper.selectAll();

   // 从数据库,数据源2(startplan)
   List<Standard2> list = standardMapper2.selectAll();

   LOGGER.debug("数据源1:" + standards);
   LOGGER.debug("数据源2:" + list);
}

在这里插入图片描述


总结

每天一个提升小技巧!!!

你可能感兴趣的:(Springboot,spring,boot,mysql)