前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot整合多数据源

SpringBoot整合多数据源

作者头像
CBeann
发布2023-12-25 18:40:08
1810
发布2023-12-25 18:40:08
举报
文章被收录于专栏:CBeann的博客CBeann的博客

需求

最近有一个需求,需要把安某服务器中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%2B8
      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%2B8
      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");
  }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 需求
  • 源码下载
  • 项目目录
  • 核心代码
    • pom.xml
      • application.yml
        • 配置两个数据源
          • 其他的也就没啥的,亲测可用
          • 未解决的问题
          相关产品与服务
          数据库
          云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档