SpringBoot整合多数据源

2023-12-25 18:40:08 浏览数 (2)

需求

最近有一个需求,需要把安某服务器中MySQL中的数据导入到另一个MySQL中,当时感觉导出到xxx.sql,然后导入进新的数据库,发现MySQL导出到xxx.sql已经实现不了了,每次导出都会卡住,时间继续,但是导出条数一直不变,后来就想了个比较 笨的方法,就是查数据库1,然后插入数据库2,所以需要SpringBoot整合多数据源,从而记录搭建环境的过程。

源码下载

SpringBoot MyBatis MySQL

https://github.com/cbeann/Demooo/tree/master/springboot-2database-demo

项目目录

核心代码

pom.xml
代码语言:javascript复制
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
application.yml
代码语言:javascript复制
erver:
  port: 8080 
spring:
  datasource:
    db2: 
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db2?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT+8
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
    db1: 
      jdbc-url: jdbc:mysql://127.0.0.1:3306/db1?characterEncoding=utf8&useUnicode=true&useSSL=false&serverTimezone=GMT+8
      username: root
      password: root
      driver-class-name: com.mysql.cj.jdbc.Driver
配置两个数据源
代码语言:javascript复制
package com.example.springboot2databasedemo.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 javax.sql.DataSource;

/**
 * @author chaird
 * @create 2020-10-30 14:21
 */
@Configuration
@MapperScan(
    basePackages = "com.example.springboot2databasedemo.dao.db1", // 扫描的dao包
    sqlSessionFactoryRef = "db1SqlSessionFactory")
public class DataSourceConfig1 {

  @Primary // 表示这个数据源是默认数据源, 这个注解必须要加,因为不加的话spring将分不清楚那个为主数据源(默认数据源)
  @Bean("db1DataSource")
  @ConfigurationProperties(prefix = "spring.datasource.db1") // 读取application.yml中的配置参数映射成为一个对象
  public DataSource getDb1DataSource() {
    return DataSourceBuilder.create().build();
  }

  @Primary
  @Bean("db1SqlSessionFactory")
  public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource)
      throws Exception {
    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    bean.setDataSource(dataSource);
    // mapper的xml形式文件位置必须要配置,不然将报错:no statement (这种错误也可能是mapper的xml中,namespace与项目的路径不一致导致)
    bean.setMapperLocations(
        new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db1/*.xml")); 扫描的daoXML包
    return bean.getObject();
  }

  @Primary
  @Bean("db1SqlSessionTemplate")
  public SqlSessionTemplate db1SqlSessionTemplate(
      @Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
  }
}
代码语言:javascript复制
package com.example.springboot2databasedemo.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 javax.sql.DataSource;

/**
 * @author chaird
 * @create 2020-10-30 14:22
 */
@Configuration
@MapperScan(basePackages = "com.example.springboot2databasedemo.dao.db2", sqlSessionFactoryRef = "db2SqlSessionFactory")
public class DataSourceConfig2 {

    @Bean("db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource getDb1DataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("db2SqlSessionFactory")
    public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/db2/*.xml"));
        return bean.getObject();
    }

    @Bean("db2SqlSessionTemplate")
    public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db2SqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
其他的也就没啥的,亲测可用

未解决的问题

如下图所示,其实我是注入了2个StudentDao 1和2,如果我在不同的包下定义相同的StudentDao,那怎么实现???

代码语言:javascript复制
//@Service
public class StudentService {

  @Autowired private StudentDao1 studentDaoDb1;
  @Autowired private StudentDao2 studentDaoDb2;

  public void transform(int id) {
    Student student = studentDaoDb1.selectByPrimaryKey(1);
    studentDaoDb2.insert(student);
    System.out.println("0ver");
  }
}

0 人点赞