springboot配置双mysql数据源

2023-11-02

这两天一直在配置双数据源,找了网上很多资料,有的资料写的太乱而且注释不清楚,类不全.像我这样的刚开始配置的新手很难看明白,今天终于配置成功了,我把我总结的整理一下,做个日志以防以后遇到问题
一.创建一个springboot项目其中需要的pom文件:

		<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.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web-services</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.0.28</version>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.16.10</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	

二.下面开始配置我们的配置文件application.properties 我的事properties文件 如果是yml文件也是一样的就是写法不同而已

spring.datasource.first.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.first.url=jdbc:mysql://192.168.100.205:3306/storage_data?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.first.username=root
spring.datasource.first.password=root
spring.datasource.first.type=com.alibaba.druid.pool.DruidDataSource

spring.datasource.second.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.second.url=jdbc:mysql://192.168.100.205:3306/lltsj?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.second.username=root
spring.datasource.second.password=root
spring.datasource.second.type=com.alibaba.druid.pool.DruidDataSource

其中first和second自己随便写,只要将两个数据源区分开就可以
三.接下来就创建文件封装类(有几个数据源就创建几个,)
1.first数据源

package com.data.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * Created by admin on 2019/11/7.
 */
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.first")
public class FirstDataProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}

2.second数据源

package com.data.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
 * Created by admin on 2019/11/7.
 */
@Data
@Component
@ConfigurationProperties(prefix = "spring.datasource.second")
public class SecondDataProperties {
    String driverClassName;
    String url;
    String username;
    String password;
}

其中@ConfigurationProperties(prefix = “spring.datasource.second”)中prefix要和配置文件中配置数据源的名字一样
四.开始创建工厂,这里的代码是最重要的
@MapperScan(basePackages = “com.data.mapper.first”,sqlSessionTemplateRef = “firstSqlSessionTemplate”)此注解basePackages地址是自己对应数据源mapper地址,sqlSessionTemplateRef是我们创建工厂的名字,是自己起的,在代码最下面,如果没有特殊需要和我一样就可以
1.first数据源工厂

package com.data.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.Autowired;
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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by admin on 2019/11/7.
 */
@Configuration
@MapperScan(basePackages = "com.data.mapper.first",sqlSessionTemplateRef = "firstSqlSessionTemplate")
public class FirstDataSourceConfig {
    @Autowired
    private FirstDataProperties firstprop;
    //配置mybatis位置
	static final String MAPPER_LOCATION = "classpath:mapping/*Mapper.xml";
    //创建数据源
    @Bean(name="firstDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.first")

    public DataSource getFirstDataSource(){
        DataSource build = DataSourceBuilder.create()
                .driverClassName(firstprop.driverClassName)
                .url(firstprop.url)
                .username(firstprop.username)
                .password(firstprop.password).build();
        return build;
    }

    //创建SqlSessionFactory
    @Bean(name = "firstSqlSessionFactory")

    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //配置mybatis的位置工厂
        bean.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(FirstDataSourceConfig.MAPPER_LOCATION));
        return bean.getObject();
    }

    //创建事务管理器
    @Bean(name = "firstTransactionManager")

    public DataSourceTransactionManager firstTransactionManager(@Qualifier("firstDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    //创建SqlSessionTemplate
    @Bean(name = "firstSqlSessionTemplate")

    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws  Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    private Class getType(String type){
        try {
            return Class.forName(type);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        return null;
    }
}

2.second数据源

package com.data.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.Autowired;
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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by admin on 2019/11/7.
 */

@Configuration
@MapperScan(basePackages = "com.data.mapper.second",sqlSessionTemplateRef = "secondSqlSessionTemplate")
public class SecondDataSourceConfig {
    @Autowired
    private SecondDataProperties secondprop;

    //创建数据源
    @Bean(name="secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    @Primary
    public DataSource getSecondDataSource(){
        DataSource build = DataSourceBuilder.create()
                .driverClassName(secondprop.driverClassName)
                .url(secondprop.url)
                .username(secondprop.username)
                .password(secondprop.password).build();
        return build;
    }

    //创建SqlSessionFactory
    @Bean(name = "secondSqlSessionFactory")
    @Primary
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean=new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();
    }

    //创建事务管理器
    @Bean(name = "secondTransactionManager")
    @Primary
    public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    //创建SqlSessionTemplate
    @Bean(name = "secondSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws  Exception{
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    private Class getType(String type){
        try {
            return Class.forName(type);
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        return null;
    }
}

这样已经能用了,剩下的用法和我们用单数据源是一样的,就是分清哪个mapper是哪个数据源的,不要搞混就OK了

import com.data.mapper.second.SecondDataMapper;
import com.data.service.DataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by admin on 2019/8/19.
 */
@Service
public class DataServiceImpl implements DataService {
    @Autowired
    private FirstDataMapper firstDataMapper;
    @Autowired
    private SecondDataMapper secondDataMapper;
    @Override
    public String firstData() {
        String a = firstDataMapper.firstData();
        String b = secondDataMapper.firstData();
        return a+b;
    }
}

还有就是在启动类中加上

package com.data;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class IndataApplication {

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

}

这是我项目的结构
在这里插入图片描述
这样就可以启动了

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

springboot配置双mysql数据源 的相关文章

随机推荐

  • c++后台开发适合入坑吗?就业前景如何?

    一 什么是c 后台开发 c 后台开发也可以叫c 后端开发 其实从技术上来说并无不同 c 后台开发就是基于linux环境和C 语言的服务器程序开发 像qq服务器 微信服务器 王者荣耀服务器等等 虽然现在各种高级语言大火 但是在高性能这一块 c
  • 旧版本Druid回收连接引发的'recyle error'

    公司官网上的心跳交易不执行了 按理说是定时任务做的 怎么会不执行呢 遂去查看日志发现 ERROR 2018 09 25 20 30 37 933 AgtForwardServiceImpl java 31 转发数据推送异常 nested e
  • 学习Python的心得体会

    随着人工智能 大数据的火热 Python成为了广大科学家和普通大众的学习语言 在学习Python的过程中 我感到迷茫不知道自己该从什么地方入手 我在学习Python之前了解过这门语言 也知道Python有很多的学习方向 比如说数据采集方向
  • 【配置跑通Omni-Swarm(omni swarm:开源的多机器人协同SLAM算法)持续踩坑排雷更新中。。。】

    配置跑通Omni Swarm omni swarm 开源的多机器人协同SLAM算法 持续踩坑排雷更新中 旨在记录跑通Omni Swarm过程 踩坑排雷 文章目录 配置跑通Omni Swarm omni swarm 开源的多机器人协同SLAM
  • linux中.tar文件怎么解压

    linux中 tar文件怎么解压 1 打包压缩tar cvf etc tar app etc 打包 tar zcvf pack tar gz pack 打包压缩为一个 gz格式的压缩包 tar jcvf pack tar bz2 pack
  • 编写.gitignore文件

    有时候我们并不想要把一个项目都提交到git上 比如一个基于当前服务器的配置 当项目迁移到另一个服务器上时 这个配置相应变成了与另一个服务器相关的 如果在提交到git服务器时连同该配置一同提交 就很容易因为未及时修改而发生错误 这时候 就需要
  • 无约束最优化问题

    估计有些读者看到这个题目的时候会觉得很数学 和自然语言处理没什么关系 不过如果你听说过最大熵模型 条件随机场 并且知道它们在自然语言处理中被广泛应用 甚至你明白其核心的参数训练算法中有一种叫LBFGS 那么本文就是对这类用于解无约束优化算法
  • var模型matlab代码_VAR模型

    前言 说来话长 这是失败的实践 前几天有个比赛 其中数据处理部分 它给出了前很多年2G 3G 4G 总无线接入网络数据规模的数据 让预测2020年5G和总的 当时一看题就觉得要用时间序列模型 多元时间序列模型就想拿VAR练练手 但是因果检验
  • 接口测试工具Apifox 基础篇:数据传递与处理

    一 接口之间如何传递数据 1 使用场景 接口B请求参数依赖于接口A返回的数据 2 实现思路 2 1 接口A使用后置操作 gt 提取变量功能将请求完成后返回的数据提取作为变量 2 2 接口B对应的参数值直接引用前面设置的变量 3 使用示例 3
  • R语言学习:数据结构2-向量

    向量 vector 只能包含同一类型的对象 创建向量 向量的类型 命名 vector x lt vector character length 10 生成指定长度的空向量 x1 lt 1 4 x2 lt c 1 2 3 x3 lt c TR
  • Apple iOS MDM开发流程

    一年前曾参与一个企业移动平台项目 实现了通过MDM对iOS设备进行管理 由于苹果对于mdm这块的接口及开发流程只向几个合作伙伴进行了分享 并没有对具体实现的文档进行公开 所以这方面的资料非常少 现在把实现的过程分享给大家 希望能对大家有所帮
  • pandas常用功能与函数介绍(结合实例,持续更新)

    本文首先介绍Pandas常用功能及函数 最后通过实例举例说明 一 常用功能及函数简介 包导入 一般我们需要做如下导入 numpy和pandas一般需要联合使用 import pandas as pd import numpy as np 本
  • meethigher-JPA实体监听器-@EntityListeners

    参考文章JPA实体类监听器 EntityListeners注解使用实例 疯狂的蜗牛 CSDN博客 entitylisteners 本文源码 这也是来源于工作中的一个小需求 因为产品迭代时 需要给前端创建人 但是由于创建人是在操作记录的表里记
  • 【linux系统基础知识-Shell脚本学习笔记12-循环】

    12 1 循环说明解释 循环是可以使你多次执行一系列命令 循环包括 for循环 while循环 select循环 for do done while do done until do done 12 2 for循环 for循环使你对列表中的
  • 用TW8836驱动ST7701S TTL屏调试记录

    近段时间做一个项目 要调试3 2寸320x820分辨率的LCD 在此做下记录 屏规格书如上图 屏的主要接口如上图 1 查看屏的规格书 如图所示 需要8836和st7701s通讯 方式是3线SPI 2 通讯接口SDA SCK CS 3 RGB
  • zabbix搭建

    1 环境 本实验使用一台centos7主机 关闭了firewalld和selinux服务 zabbix版本为5 0版本 mysql使用版本为5 7版本 若要搭建6 0以上版本的zabbix 则需要使用mysql 8 0以上的版本 其它版本的
  • 微信公众号获取用户的openid

    公众号可获得关注者的OpenID 加密后的微信号 每个用户对每个公众号的OpenID是唯一的 对于不同公众号 同一用户的openid不同 公众号可通过本接口来根据OpenID获取用户基本信息 包括昵称 头像 性别 所在城市 语言和关注时间
  • shell 脚本中 $$、$#、$? 分别代表什么意思?

    0 这个程式的执行名字 n 这个程式的第 n 个参数值 n 1 9 这个程式的所有参数 此选项参数可超过 9 个 这个程式的参数个数 这个程式的 PID 脚本运行的当前进程 ID 号 执行上一个背景指令的 PID 后台运行的最后一个进程的进
  • Ubuntu16.04 ARM/Qt 交叉编译环境搭建

    嵌入式开发 Ubuntu16 04 ARM Qt 交叉编译环境搭建 背景 环境说明 安装交叉编译工具 下载Qt源码包 编译Qt源码 安装QtCreator 配置QtCreator 应用QtCreator交叉编译 Ubuntu16 04 AR
  • springboot配置双mysql数据源

    这两天一直在配置双数据源 找了网上很多资料 有的资料写的太乱而且注释不清楚 类不全 像我这样的刚开始配置的新手很难看明白 今天终于配置成功了 我把我总结的整理一下 做个日志以防以后遇到问题 一 创建一个springboot项目其中需要的po