在开发微服务的过程中,有时我们的服务需要连接两个以上的数据库进行业务数据的CRUD操作,这时候就需要我们进行多数据源的配置。

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.tl</groupId>
        <artifactId>hello-spring-boot-dependencies</artifactId>
        <version>1.0.0</version>
        <relativePath>../hello-spring-boot-dependencies/pom.xml</relativePath>
    </parent>

    <artifactId>hello-spring-boot-mybatis-druid</artifactId>
    <packaging>jar</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!--devtools热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- mysql8 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- Swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
    </dependencies>

</project>

主要配置文件

datasource.properties

druid.primary.jdbc-url=jdbc:mysql://localhost:3306/source_data
druid.primary.username=root
druid.primary.password=root
druid.primary.driver-class-name=com.mysql.cj.jdbc.Driver
druid.second.jdbc-url=jdbc:mysql://localhost:3306/target_data
druid.second.username=root
druid.second.password=root
druid.second.driver-class-name=com.mysql.cj.jdbc.Driver

数据库连接池配置

PrimaryDataSource.java

package com.tl.hello.spring.boot.mybatis.druid.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author tianl
 * @date 2020/3/27 22:11
 */
@Configuration
@MapperScan(basePackages = {"com.tl.hello.spring.boot.mybatis.druid.dao.primary"}, sqlSessionFactoryRef = "primarySqlSessionFactory")
@PropertySource("classpath:config/datasource.properties")
public class PrimaryDataSourceConfig {

    @Value("${druid.primary.jdbc-url}")
    private String jdbcUrl;

    @Value("${druid.primary.username}")
    private String username;

    @Value("${druid.primary.password}")
    private String password;

    @Value("${druid.primary.driver-class-name}")
    private String driverClassName;


    @Bean(name = {"primaryDataSource"})
    @Primary
    public DruidDataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(jdbcUrl);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setDriverClassName(driverClassName);
        return druidDataSource;
    }

    @Bean(name = "primaryTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(this.dataSource());
    }

    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/sourcedata/*Mapper.xml"));
        return sessionFactory.getObject();
    }

}

SecondDataSource.java

package com.tl.hello.spring.boot.mybatis.druid.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author tianl
 * @date 2020/3/27 22:53
 */
@Configuration
@MapperScan(basePackages = {"com.tl.hello.spring.boot.mybatis.druid.dao.second"}, sqlSessionFactoryRef = "secondSqlSessionFactory")
@PropertySource("classpath:config/datasource.properties")
public class SecondDataSourceConfig {
    @Value("${druid.second.jdbc-url}")
    private String jdbcUrl;

    @Value("${druid.second.username}")
    private String username;

    @Value("${druid.second.password}")
    private String password;

    @Value("${druid.second.driver-class-name}")
    private String driverClassName;

    @Bean(name = "secondDataSource")
    public DruidDataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(jdbcUrl);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setDriverClassName(driverClassName);
        return druidDataSource;
    }

    @Bean(name = "secondTransactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(this.dataSource());
    }

    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath:mapper/targetdata/*Mapper.xml"));
        return sessionFactory.getObject();
    }

}

测试:启动一个定时任务同步连个数据中数据

package com.tl.hello.spring.boot.mybatis.druid.service;

import com.tl.hello.spring.boot.mybatis.druid.model.primary.PrimaryUser;
import com.tl.hello.spring.boot.mybatis.druid.model.second.SecondUser;
import com.tl.hello.spring.boot.mybatis.druid.service.primary.PrimaryUserService;
import com.tl.hello.spring.boot.mybatis.druid.service.second.SecondUserService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author tianl
 * @date 2020/3/28 0:51
 */
@Service
public class syncDataService {

    @Resource
    private PrimaryUserService primaryUserService;

    @Resource
    private SecondUserService secondUserService;

    @Scheduled(cron = "0/5 * * * * ?")
    public void sync() {
        PrimaryUser primaryUser = primaryUserService.selectByPrimaryKey(19L);
        SecondUser secondUser = new SecondUser();
        secondUser.setAge(primaryUser.getAge());
        secondUser.setName(primaryUser.getName());
        secondUser.setUsername(primaryUser.getUsername());
        secondUser.setPassword(primaryUser.getPassword());
        secondUserService.insertOrUpdate(secondUser);
    }
}

代码完成地址:[码云]

03-05 16:51