SpringBoot2集成Mybatis Druid多数据源配置

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

pom.xml



    4.0.0
    
        com.tl
        hello-spring-boot-dependencies
        1.0.0
        ../hello-spring-boot-dependencies/pom.xml
    

    hello-spring-boot-mybatis-druid
    jar

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-test
        
        
        
            org.springframework.boot
            spring-boot-devtools
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
        
            mysql
            mysql-connector-java
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
        

        
            com.alibaba
            druid-spring-boot-starter
        

        
        
            org.projectlombok
            lombok
        

        
        
            io.springfox
            springfox-swagger2
        
        
            io.springfox
            springfox-swagger-ui
        
        
            org.apache.commons
            commons-lang3
        
    

主要配置文件

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);
    }
}

代码完成地址:[码云]

你可能感兴趣的:(springboot,druid,数据库连接池,多数据源)