Spring Boot 2 整合 Mybatis 多数据源

文章目录

      • 1 摘要
      • 2 核心代码
        • 2.1 配置文件
        • 2.2 代码中配置数据源
        • 2.3 SpringBoot 启动类
        • 2.4 多数据源应用与测试
      • 3 参考文档推荐
      • 4 Github 源码


1 摘要

在一个项目中连接多个数据源并不是常有的需求,但是在多个项目整合的时候,可能会用到。本文将介绍在 SpringBoot 2.X 项目中整合 Mybatis 多个数据源的方法。

2 核心代码

2.1 配置文件

主配置信息

../demo-schedule/src/main/resources/application.yml
## spring config

# tomcat server
server:
  use-forward-headers: true
  tomcat:
    remote-ip-header: x-forwarded-for
    protocol-header: x-forwarded-proto
    port-header: X-Forwarded-Port

## spring config
spring:
  # environment: dev|test|pro
  profiles:
    active: dev
  # datasource connect-pool
  datasource:
    druid:
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
      initial-size: 5
      max-active: 20
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
  # multipart file
  servlet:
    multipart:
      # single file max size
      max-file-size: 10mb
      # multi file max size
      max-request-size: 100mb

## mybatis
mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.ljq.demo.springboot.entity

## mybatis log
logging:
  level:
    com.ljq.demo.springboot.dao: debug

不同环境配置信息

../demo-schedule/src/main/resources/application-dev.yml
../demo-schedule/src/main/resources/application-pro.yml
../demo-schedule/src/main/resources/application-test.yml

不同的环境,对应的数据库配置不同,但是格式一样,这里以application-dev.yml 为例:

## environment-dev

## tomcat server
server:
  port: 8848

spring:
  ## datasource
  datasource:
    user:
      url: "jdbc:mysql://192.168.100.100:3306/demo?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true\
          &useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true&allowMultiQueries=true&autoReconnect=true"
      username: root
      password: root
    receiveAddress:
      url: "jdbc:mysql://192.168.100.100:3306/demo1?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true\
                &useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true&allowMultiQueries=true&autoReconnect=true"
      username: root
      password: root

这里有两个数据源,分别是 userredeiveAddress

2.2 代码中配置数据源

项目中包含多个数据源时,需要指定一个主数据源,这里将 user 数据源作为主数据源

用户 user 数据源配置:

../demo-schedule/src/main/java/com/ljq/demo/springboot/schedule/common/config/DataSourceUserConfig.java
package com.ljq.demo.springboot.schedule.common.config;

import lombok.extern.slf4j.Slf4j;
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @Description: 数据源配置-user(主数据源)
 * @Author: junqiang.lu
 * @Date: 2019/6/16
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"com.ljq.demo.springboot.dao.user"},sqlSessionTemplateRef = "sqlSessionTemplateUser")
public class DataSourceUserConfig {

    @Autowired
    private ConfigurableEnvironment env;

    /**
     * 数据源配置
     *
     * @return
     */
    @Bean(name = "dataSourceUser")
    @ConfigurationProperties(prefix = "spring.datasource.user")
    @Primary
    public DataSource dataSource() {
        log.info("{}"," 【user】初始化数据源配置");
        log.debug("\n driverClassName: {},\n url: {},\n username: {},\n password: {}",
                env.getProperty("spring.datasource.druid.driver-class-name"),
                env.getProperty("spring.datasource.user.url"),
                env.getProperty("spring.datasource.user.username"),
                env.getProperty("spring.datasource.user.password"));
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.druid.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.user.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.user.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.user.password"));
        return dataSource;
    }

    /**
     * 数据会话工厂
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "sqlSessionFactoryUser")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSourceUser") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 仅当使用 Mapper 文件存放SQL时设置该部分;如果使用注解方式写SQL语句,则不设置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapper-locations")));
        factoryBean.setTypeAliasesPackage(env.getProperty("mybatis.type-aliases-package"));

        return factoryBean.getObject();
    }

    /**
     * 数据库事务管理
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "transactionManagerUser")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSourceUser") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 数据库会话实例
     *
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "sqlSessionTemplateUser")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactoryUser") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

收货地址数据源(receiveAddress) 配置信息:

../demo-schedule/src/main/java/com/ljq/demo/springboot/schedule/common/config/DataSourceReceiveAddressConfig.java
package com.ljq.demo.springboot.schedule.common.config;

import lombok.extern.slf4j.Slf4j;
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @Description: 数据源配置-receiveAddress
 * @Author: junqiang.lu
 * @Date: 2019/6/16
 */
@Slf4j
@Configuration
@MapperScan(basePackages = {"com.ljq.demo.springboot.dao.receiveaddress"},sqlSessionTemplateRef = "sqlSessionTemplateReceiveAddress")
public class DataSourceReceiveAddressConfig {

    @Autowired
    private ConfigurableEnvironment env;

    /**
     * 数据源配置
     *
     * @return
     */
    @Bean(name = "dataSourceReceiveAddress")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        log.info("{}"," 【receiveAddress】初始化数据源配置");
        log.debug("\n driverClassName: {},\n url: {},\n username: {},\n password: {}",
                env.getProperty("spring.datasource.druid.driver-class-name"),
                env.getProperty("spring.datasource.receiveAddress.url"),
                env.getProperty("spring.datasource.receiveAddress.username"),
                env.getProperty("spring.datasource.receiveAddress.password"));
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(env.getProperty("spring.datasource.druid.driver-class-name"));
        dataSource.setUrl(env.getProperty("spring.datasource.receiveAddress.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.receiveAddress.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.receiveAddress.password"));
        return dataSource;
    }

    /**
     * 数据会话工厂
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    @Bean(name = "sqlSessionFactoryReceiveAddress")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSourceReceiveAddress") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 仅当使用 Mapper 文件存放SQL时设置该部分;如果使用注解方式写SQL语句,则不设置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapper-locations")));
        factoryBean.setTypeAliasesPackage(env.getProperty("mybatis.type-aliases-package"));

        return factoryBean.getObject();
    }

    /**
     * 数据库事务管理
     *
     * @param dataSource
     * @return
     */
    @Bean(name = "transactionManagerReceiveAddress")
    public DataSourceTransactionManager transactionManager(@Qualifier("dataSourceReceiveAddress") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 数据库会话实例
     *
     * @param sqlSessionFactory
     * @return
     */
    @Bean(name = "sqlSessionTemplateReceiveAddress")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactoryReceiveAddress") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

注意: 数据源配置类中有一些需要注意的地方,在主数据源中需要使用 @Primary 注解用以声明主数据源;配置类上的 @MapperScan 注解的basePackages 方法需要根据不同的数据源对应不同的包,所指定的包名可以不在当前模块下;数据源的配置信息读取则要与 application.yml 配置文件中保持一致;在使用 mapper.xml 文件存储 SQL 文件时需要设置以下选项:

// 仅当使用 Mapper 文件存放SQL时设置该部分;如果使用注解方式写SQL语句,则不设置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapper-locations")));
        factoryBean.setTypeAliasesPackage(env.getProperty("mybatis.type-aliases-package"));

其中 mybatis.mapper-locationsmybatis.type-aliases-package 参考主配置文件(application.yml) 中的配置

2.3 SpringBoot 启动类

../demo-schedule/src/main/java/com/ljq/demo/springboot/schedule/DemoScheduleApplication.java
package com.ljq.demo.springboot.schedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @author junqiang.lu
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class},scanBasePackages = {"com.ljq.demo.springboot"})
@EnableScheduling
public class DemoScheduleApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoScheduleApplication.class, args);
    }

}

由于使用了多个数据源,因此需要禁止 Spring Boot 自动配置数据源,在 @SpringBootApplication 中添加 exclude = {DataSourceAutoConfiguration.class} ,同时需要指定组件(component) 扫描范围,确保 DAO 层,数据源配置等能够在 SpringBoot 项目启动后自动装配

2.4 多数据源应用与测试

../demo-schedule/src/main/java/com/ljq/demo/springboot/schedule/cronjob/MultiDataSourceDemoSchedule.java
package com.ljq.demo.springboot.schedule.cronjob;

import com.ljq.demo.springboot.dao.receiveaddress.ReceiveAddressDao;
import com.ljq.demo.springboot.dao.user.UserDao;
import com.ljq.demo.springboot.entity.ReceiveAddressEntity;
import com.ljq.demo.springboot.entity.UserDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * @Description: 多数据源示例定时任务
 * @Author: junqiang.lu
 * @Date: 2019/6/16
 */
@Slf4j
@Component
public class MultiDataSourceDemoSchedule {

    @Autowired
    private UserDao userDao;

    @Autowired
    private ReceiveAddressDao receiveAddressDao;

    /**
     * 用户列表定时任务
     */
    @Scheduled(fixedDelay = 10 * 1000, initialDelay = 10 * 1000)
    public void userListSchedule() {
        int userCount = userDao.queryCount(new HashMap<>(16));
        log.debug("userCount: {}", userCount);
        if (userCount > 0) {
            List<UserDO> userDBList = userDao.queryList(null);
            userDBList.stream().forEach(userDO -> {
                log.debug("{}", userDO);
            });
        }
    }

    /**
     * 收货地址列表定时任务
     */
    @Scheduled(fixedDelay = 10 * 1000, initialDelay = 10 * 1000)
    public void receiveAddressListSchedule() {
        int receiveAddressCount = receiveAddressDao.queryCount(new HashMap<>(16));
        log.debug("receiveAddressCount: {}", receiveAddressCount);
        if (receiveAddressCount > 0) {
            List<ReceiveAddressEntity> receiveAddressDBList = receiveAddressDao.queryList(null);
            receiveAddressDBList.stream().forEach(receiveAddressEntity -> {
                log.debug("{}", receiveAddressEntity);
            });
        }
    }


}

这里 UserDao 使用的是 user 数据源; ReceiveAddressDao 使用的是 receiveAddress 数据源

项目启动之后的日志:

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.6.RELEASE)

2019-06-18 15:00:42 | INFO  | restartedMain | c.l.d.springboot.schedule.DemoScheduleApplicationStartupInfoLogger.java 50| Starting DemoScheduleApplication on DESKTOP-QE5EKK7 with PID 14652 (D:\develop\repository\git\springBootDemo\demo-schedule\target\classes started by Caleb in D:\develop\repository\git\springBootDemo)
2019-06-18 15:00:42 | DEBUG | restartedMain | c.l.d.springboot.schedule.DemoScheduleApplicationStartupInfoLogger.java 53| Running with Spring Boot v2.0.6.RELEASE, Spring v5.0.10.RELEASE
2019-06-18 15:00:42 | INFO  | restartedMain | c.l.d.springboot.schedule.DemoScheduleApplicationSpringApplication.java 658| The following profiles are active: dev
2019-06-18 15:00:42 | INFO  | restartedMain | o.s.c.a.AnnotationConfigApplicationContextAbstractApplicationContext.java 588| Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@199fd77c: startup date [Tue Jun 18 15:00:42 CST 2019]; root of context hierarchy
2019-06-18 15:00:43 | INFO  | restartedMain | o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorCheckerPostProcessorRegistrationDelegate.java 326| Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$d5602105] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-06-18 15:00:43 | INFO  | restartedMain | c.l.d.s.s.common.config.DataSourceUserConfigDataSourceUserConfig.java 43|  【user】初始化数据源配置
2019-06-18 15:00:43 | DEBUG | restartedMain | c.l.d.s.s.common.config.DataSourceUserConfigDataSourceUserConfig.java 44| 
 driverClassName: com.mysql.cj.jdbc.Driver,
 url: jdbc:mysql://192.168.100.100:3306/demo?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true&allowMultiQueries=true&autoReconnect=true,
 username: root,
 password: root
2019-06-18 15:00:43 | INFO  | restartedMain | o.s.jdbc.datasource.DriverManagerDataSourceDriverManagerDataSource.java 133| Loaded JDBC driver: com.mysql.cj.jdbc.Driver
2019-06-18 15:00:43 | DEBUG | restartedMain | org.apache.ibatis.logging.LogFactoryLogFactory.java 135| Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
2019-06-18 15:00:43 | INFO  | restartedMain | c.l.d.s.s.c.config.DataSourceReceiveAddressConfigDataSourceReceiveAddressConfig.java 41|  【receiveAddress】初始化数据源配置
2019-06-18 15:00:43 | DEBUG | restartedMain | c.l.d.s.s.c.config.DataSourceReceiveAddressConfigDataSourceReceiveAddressConfig.java 42| 
 driverClassName: com.mysql.cj.jdbc.Driver,
 url: jdbc:mysql://192.168.100.100:3306/demo1?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=true&allowMultiQueries=true&autoReconnect=true,
 username: root,
 password: root
2019-06-18 15:00:43 | INFO  | restartedMain | o.s.jdbc.datasource.DriverManagerDataSourceDriverManagerDataSource.java 133| Loaded JDBC driver: com.mysql.cj.jdbc.Driver
2019-06-18 15:00:43 | INFO  | restartedMain | o.s.b.d.autoconfigure.OptionalLiveReloadServerOptionalLiveReloadServer.java 57| LiveReload server is running on port 35729
2019-06-18 15:00:43 | INFO  | restartedMain | o.s.jmx.export.annotation.AnnotationMBeanExporterMBeanExporter.java 433| Registering beans for JMX exposure on startup
2019-06-18 15:00:43 | INFO  | restartedMain | o.s.jmx.export.annotation.AnnotationMBeanExporterMBeanExporter.java 895| Bean with name 'statFilter' has been autodetected for JMX exposure
2019-06-18 15:00:43 | INFO  | restartedMain | o.s.jmx.export.annotation.AnnotationMBeanExporterMBeanExporter.java 668| Located MBean 'statFilter': registering with JMX server as MBean [com.alibaba.druid.filter.stat:name=statFilter,type=StatFilter]
2019-06-18 15:00:43 | INFO  | restartedMain | o.s.s.a.ScheduledAnnotationBeanPostProcessorScheduledAnnotationBeanPostProcessor.java 276| No TaskScheduler/ScheduledExecutorService bean found for scheduled processing
2019-06-18 15:00:43 | INFO  | restartedMain | c.l.d.springboot.schedule.DemoScheduleApplicationStartupInfoLogger.java 59| Started DemoScheduleApplication in 1.971 seconds (JVM running for 2.637)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.d.r.ReceiveAddressDao.queryCountBaseJdbcLogger.java 159| ==>  Preparing: select count(*) from receive_address 
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.d.r.ReceiveAddressDao.queryCountBaseJdbcLogger.java 159| ==> Parameters: 
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.d.r.ReceiveAddressDao.queryCountBaseJdbcLogger.java 159| <==      Total: 1
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 51| receiveAddressCount: 6
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.d.r.ReceiveAddressDao.queryListBaseJdbcLogger.java 159| ==>  Preparing: select * from receive_address ORDER BY id DESC LIMIT 0, 5 
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.d.r.ReceiveAddressDao.queryListBaseJdbcLogger.java 159| ==> Parameters: 
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.d.r.ReceiveAddressDao.queryListBaseJdbcLogger.java 159| <==      Total: 5
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 55| ReceiveAddressEntity(id=6, userId=6, receiverName=小白, telephone=13111111116, province=湖北省, city=武汉市, area=武昌区, address=xxx路xxx小区xxx单元, defaultAddress=1)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 55| ReceiveAddressEntity(id=5, userId=5, receiverName=小红, telephone=13111111115, province=河南市, city=郑州市, area=中原区, address=xxx路xxx小区xxx单元, defaultAddress=1)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 55| ReceiveAddressEntity(id=4, userId=4, receiverName=小明, telephone=13111111114, province=上海市, city=上海市市辖区, area=黄浦区, address=xxx路xxx小区xxx单元, defaultAddress=1)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 55| ReceiveAddressEntity(id=3, userId=3, receiverName=王五, telephone=13111111113, province=江西省, city=南昌市, area=东湖区, address=xxx路xxx小区xxx单元, defaultAddress=1)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 55| ReceiveAddressEntity(id=2, userId=2, receiverName=李四, telephone=13111111112, province=四川省, city=成都市, area=锦江区, address=xxx路xxx小区xxx单元, defaultAddress=1)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.ljq.demo.springboot.dao.user.UserDao.queryCountBaseJdbcLogger.java 159| ==>  Preparing: select count(*) counts from `user` where `user_del` = 0 ORDER BY id DESC LIMIT 0, 5 
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.ljq.demo.springboot.dao.user.UserDao.queryCountBaseJdbcLogger.java 159| ==> Parameters: 
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.ljq.demo.springboot.dao.user.UserDao.queryCountBaseJdbcLogger.java 159| <==      Total: 1
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 36| userCount: 5
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | com.ljq.demo.springboot.dao.user.UserDao.queryListBaseJdbcLogger.java 159| ==>  Preparing: select u.id, u.user_name, u.user_passcode, u.user_email, u.user_insert_time, u.user_update_time, u.user_status, u.user_version, u.user_del from `user` u where u.user_del = 0 ORDER BY id DESC LIMIT 0, 5 
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | com.ljq.demo.springboot.dao.user.UserDao.queryListBaseJdbcLogger.java 159| ==> Parameters: 
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | com.ljq.demo.springboot.dao.user.UserDao.queryListBaseJdbcLogger.java 159| <==      Total: 5
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 40| UserDO(id=5, userName=liming, userPasscode=ed0de7252acf2980e677bacab01bde25, [email protected], userInsertTime=2019-06-12 17:42:40, userUpdateTime=2019-06-12 17:42:40, userStatus=1, userVersion=1, userDel=0)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 40| UserDO(id=4, userName=lily, userPasscode=ed0de7252acf2980e677bacab01bde25, [email protected], userInsertTime=2019-06-12 17:42:40, userUpdateTime=2019-06-12 17:42:40, userStatus=1, userVersion=1, userDel=0)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 40| UserDO(id=3, userName=jack, userPasscode=ed0de7252acf2980e677bacab01bde25, [email protected], userInsertTime=2019-06-12 17:42:40, userUpdateTime=2019-06-12 17:42:40, userStatus=1, userVersion=1, userDel=0)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 40| UserDO(id=2, userName=bob, userPasscode=ed0de7252acf2980e677bacab01bde25, [email protected], userInsertTime=2019-06-12 17:42:40, userUpdateTime=2019-06-12 17:42:40, userStatus=1, userVersion=1, userDel=0)
2019-06-18 15:00:53 | DEBUG | pool-2-thread-1 | c.l.d.s.s.cronjob.MultiDataSourceDemoScheduleMultiDataSourceDemoSchedule.java 40| UserDO(id=1, userName=tom, userPasscode=ed0de7252acf2980e677bacab01bde25, [email protected], userInsertTime=2019-06-12 17:42:40, userUpdateTime=2019-06-12 17:42:40, userStatus=1, userVersion=1, userDel=0)

日志可以看出两个数据源都加载了,同时引用不同的 Dao 层,使用不同的数据源,至此 SpringBoot + Mybatis 配置多数据源的功能已经实现

3 参考文档推荐

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Spring Profiles

springboot+mybatis 多数据源——Mybatis深入浅出(三)

4 Github 源码

Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo

个人公众号:404Code,分享半个互联网人的技术与思考,感兴趣的可以关注.
Spring Boot 2 整合 Mybatis 多数据源_第1张图片

你可能感兴趣的:(Java)