Java中SringBoot服务连接多个MySQL数据源案例实战

news2024/9/21 2:39:04

Java中SringBoot服务连接多个MySQL数据源案例实战

    • 1.场景
    • 2.取消默认的单数据源配置
    • 3.自定义多数据源配置文件
    • 4.自定义多数据源配置类
      • 1.DB1Config.java
      • 2.DB2Config.java
    • 5.启动项目,测试操作多数据源

1.场景

A服务(供应商)有一套自己的数据库db1;B服务(二次开发)也有一套自己的数据库db2;从B服务查询db1中的一些数据,需要B服务同时链接2个数据库源。

2.取消默认的单数据源配置

在这里插入图片描述

修改启动类的@SpringBootApplication注解,(将org.example.db.**.mapper替换为自己项目的mapper文件目录)

@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
@MapperScan({"org.example.db1.**.mapper","org.example.db1.**.mapper"})
public class TestApplication{
	...
}

3.自定义多数据源配置文件

在这里插入图片描述

在application.properties 文件(或nacos配置文件)中配置以下数据库连接源:

spring:
  # 数据源配置
  datasource:
    db1:
      jdbc-url: xxxxxxxxxxxxxx
      username: xxxxxxxxxxxxxx
      password: xxxxxxxxxxxxxx
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver
    db2:
      jdbc-url: xxxxxxxxxxxxxx
      username: xxxxxxxxxxxxxx
      password: xxxxxxxxxxxxxx
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.cj.jdbc.Driver

4.自定义多数据源配置类

在这里插入图片描述

1.DB1Config.java

将org.example.db1.**.mapper替换为自己项目的mapper文件目录

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
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 javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "org.example.db1.**.mapper",sqlSessionFactoryRef = "db1SqlSessionFactory")
public class DB1Config {
    
    @Primary
    @Bean(name = "db1DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db1")
    public DataSource initDataSource(){
        return DataSourceBuilder.create().build();
    }
    
    @Primary
    @Bean(name = "db1SqlSessionFactory")
    public SqlSessionFactory initSqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setDbConfig(new GlobalConfig.DbConfig().setUpdateStrategy(FieldStrategy.IGNORED));
        bean.setGlobalConfig(globalConfig);
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setMapUnderscoreToCamelCase(false);
        bean.setConfiguration(mybatisConfiguration);
        bean.setPlugins(new Interceptor[]{mybatisPlusInterceptor()});
        SqlSessionFactory sessionFactory = bean.getObject();
        org.apache.ibatis.session.Configuration configuration = sessionFactory.getConfiguration();
        configuration.setMapUnderscoreToCamelCase(false);
        return sessionFactory;
    }

    @Primary
    @Bean(name = "db1mybatisPlusInterceptor")
    public Interceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }
    
    
    @Primary
    @Bean(name = "db1DataSourceTransactionManager")
    public DataSourceTransactionManager initDataSourceTransactionManager(@Qualifier("db1DataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }

    @Primary
    @Bean(name = "db1SqlSessionTemplate")
    public SqlSessionTemplate initSqlSessionTemplate(@Qualifier("db1SqlSessionFactory")SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
    
}

2.DB2Config.java

数据库 db2 的配置类要将 @Primary 注解去掉

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
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 javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "org.example.db2.**.mapper",sqlSessionFactoryRef = "db2SqlSessionFactory")
public class DB2Config {

    @Bean(name = "db2DataSource")
    @ConfigurationProperties(prefix = "spring.datasource.db2")
    public DataSource initDataSource(){
        return DataSourceBuilder.create().build();
    }
    
    @Bean(name = "db2SqlSessionFactory")
    public SqlSessionFactory initSqlSessionFactory(@Qualifier("db2DataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setDbConfig(new GlobalConfig.DbConfig().setUpdateStrategy(FieldStrategy.IGNORED));
        bean.setGlobalConfig(globalConfig);
        MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
        mybatisConfiguration.setMapUnderscoreToCamelCase(false);
        bean.setConfiguration(mybatisConfiguration);
        bean.setPlugins(new Interceptor[]{mybatisPlusInterceptor()});
        SqlSessionFactory sessionFactory = bean.getObject();
        org.apache.ibatis.session.Configuration configuration = sessionFactory.getConfiguration();
        configuration.setMapUnderscoreToCamelCase(false);
        return sessionFactory;
    }

  
    @Bean(name = "db2mybatisPlusInterceptor")
    public Interceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }



    @Bean(name = "db2DataSourceTransactionManager")
    public DataSourceTransactionManager initDataSourceTransactionManager(@Qualifier("db2DataSource") DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
    
    @Bean(name = "db2SqlSessionTemplate")
    public SqlSessionTemplate initSqlSessionTemplate(@Qualifier("db2SqlSessionFactory")SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

5.启动项目,测试操作多数据源

在这里插入图片描述

在这里插入图片描述

项目启动后,控制台中看到以下内容即为配置成功

HikariPool-1 - Starting…
HikariPool-1 - Start completed.
HikariPool-2 - Starting…
HikariPool-2 - Start completed.

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2125449.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

每周心赏|教师节“AI大礼包”:3款教学神器让你AI不释手

教师节“AI大礼包”真的来了! 家人们谁懂啊,当学生时不想上课,当老师后不想上班…… 3款超会整活的教师必备AI神器,终于让我给挖到了:一键拥有金牌名师教学经验,助力撰写教案、高效赋能学生、总结工作成果…

10BASE-T1S 接口转换器

10BASE-T1S 接口工具 车载网络的发展正在经历一场转型变革,点对点和总线拓扑的融合现在已成为现实。为应对这一变革,我们推出了新颖的 10BASE-T1S 接口转换器,这是一款创新的以太网桥接器,它弥合了这两种不断发展的技术之间的差距…

【Python机器学习】循环神经网络(RNN)——对RNN进行预测

目录 有状态性 双向RNN 编码向量 如果有一个经过训练的模型,接下来就可以对其进行预测: sample_1""" I hate that the dismal weather had me down for so long,when will it break! Ugh,when does happiness return? The sun is bl…

《深入浅出多模态》之多模态经典模型:InstructBLIP

🎉AI学习星球推荐: GoAI的学习社区 知识星球是一个致力于提供《机器学习 | 深度学习 | CV | NLP | 大模型 | 多模态 | AIGC 》各个最新AI方向综述、论文等成体系的学习资料,配有全面而有深度的专栏内容,包括不限于 前沿论文解读、资料共享、行业最新动态以、实践教程、求职…

FlinkCDC 3.2.0 新增优点 Pattern Replacement in routing rules

新增优点&#xff1a;Pattern Replacement in routing rules flinkcdc 3.2.0版本相较于3.1.0版本&#xff0c;避免了多表多sink多次写 route 路由的麻烦&#xff0c;类似于统一前后缀的形式多表多sink&#xff0c;通过<>正则&#xff0c;大大减少了书写 官网&#xff1…

年薪30W的项目经理,都在用这个方法做项目!

看到很多新手项目经理不知道在带项目的时候应该怎么做&#xff0c;这里给大家整理了一份超牛的资深项目经理在日常工作中的带项目方法&#xff0c;大家有需要的可以收藏哦~&#xff01; 捋清思路&#xff0c;制定章程 在接手到一个新的项目时&#xff0c;项目经理要做的并不是…

农业品牌宣传:让绿色故事传遍万家!

合作咨询联系竑图 hongtu201988 乡村要振兴&#xff0c;品牌必须响亮&#xff01;农产品企业在追求渠道拓展与销量增长的同时&#xff0c;绝不能忽视品牌形象构建的基石作用。若缺乏稳固的品牌支撑&#xff0c;即便是再广阔的渠道与惊人的销量&#xff0c;也可能如同沙上建塔&…

灵魂绑定Tokens介绍和在Sui上的案例

灵魂绑定token&#xff08;Soulbound token&#xff0c;SBT&#xff09;这一术语由以太坊联合创始人Vitalik Buterin提出&#xff0c;是一种设计为永久且不可转让的NFT。与典型的NFT可以自由交易不同&#xff0c;SBT始终绑定于原始账户&#xff0c;就像游戏中的技能或成就一样与…

探索Python的隐秘角落:Keylogger库的神秘面纱

文章目录 探索Python的隐秘角落&#xff1a;Keylogger库的神秘面纱背景&#xff1a;为何需要Keylogger&#xff1f;库简介&#xff1a;什么是Keylogger&#xff1f;安装指南&#xff1a;如何将Keylogger纳入你的项目&#xff1f;函数使用&#xff1a;5个简单函数的介绍与代码示…

vue3 使用 codemirror 实现yaml文件的在线编辑

vue3 使用 codemirror 实现yaml文件的在线编辑 1. 使用情形2. 插件下载3. 封装yaml编辑器组件4. 父组件使用5. js-yaml 使用6. 备注 1. 使用情形 需要对yaml文件进行在线编辑&#xff0c;并且进行基础格式验证 2. 插件下载 vue-codemirror 在线代码编辑器插件 js-yaml 用于转…

RickdiculouslyEasy-CTF-综合靶场

步骤一&#xff1a;利用Goby搜索靶机地址 步骤二&#xff1a;访问靶机地址 步骤二&#xff1a;扫描端口 nmap 172.16.1.7 -p 1-65535 步骤三&#xff1a; 扫描目录 dirsearch -u http://172.16.1.7/ 第一个flag&#xff1a;命令&#xff1a;nmap -A -v -T4 172.16.1.7 -p 1-6…

MUR2060CTR-ASEMI快恢复二极管对管MUR2060CTR

编辑&#xff1a;ll MUR2060CTR-ASEMI快恢复二极管对管MUR2060CTR 型号&#xff1a;MUR2060CTR 品牌&#xff1a;ASEMI 封装&#xff1a;TO-220AB 安装方式&#xff1a;插件 批号&#xff1a;最新 最大平均正向电流&#xff08;IF&#xff09;&#xff1a;20A 最大循环…

Origin2024中绘制多因子分组柱状图,直观展示不同组别内的数据变化!

当我们需要对比多组平行数据时&#xff0c;采用Origin多因子分组柱状图&#xff0c;不仅可以直接的对比多组数据&#xff0c;同时还能够直观展示各个指标因子的数据变化及趋势 操作步骤&#xff1a; 1、先打开Origin2024软件&#xff0c;然后在Book1中输入如下示例数据&#…

边缘检测运用

文章目录 一、简介1.边缘检测的概念2.边缘检测的目的 二、代码实现三、边缘检测的方法1.1Canny边缘检测器1.2.Canny代码实现2.1Sobel边缘检测器2.2Sobel代码实现3.1Laplacian边缘检测器3.2Laplacian代码实现4.1Scharr边缘检测器4.2Scharr代码实现 四、边缘检测的应用 一、简介 …

Qt与MQTT交互通信

MQTT全称是&#xff08;Message Queuing Telemetry Transport&#xff09;&#xff0c;即消息队列遥测传输协议 是一种基于发布/订阅&#xff08;Publish/Subscribe&#xff09;模式的轻量级通讯协议&#xff0c;并且该协议构建于TCP/IP协议之上&#xff0c;常用于互联网中&am…

vue3封装数字上下滚动翻牌器,

优点&#xff1a;可以传入字符串设置初始数字位数&#xff0c;也可以直接传入数字&#xff0c;让他自己根据位数渲染 组件代码&#xff1a; <template><div class"count-flop" :key"compKey"><!-- --><div:class"item ! . ?…

【EI会议征稿通知】第四届材料工程与应用力学国际学术会议(ICMEAAE 2025)

第四届材料工程与应用力学国际学术会议&#xff08;ICMEAAE 2025&#xff09; 2025 4th International Conference on Materials Engineering and Applied Mechanics 本次会议将重点讨论材料科学、应用力学等领域的最新研究进展与发展趋势。会议旨在为国内外从事这些领域研究…

怎么利用接口发送图文彩信

在数字化时代&#xff0c;信息的传递方式日新月异&#xff0c;从传统的书信、电话到如今的即时通讯软件、社交媒体&#xff0c;每一种新技术的应用都在不断重塑我们的沟通方式。而在这其中&#xff0c;彩信&#xff08;Multimedia Messaging Service, MMS&#xff09;作为一种融…

python安装tensorflow一直报错

python安装tensorflow一直报错&#xff0c;试了3.5、3.6、3.7、3.8、3.9、3.10&#xff0c;人麻&#xff0c;全部都不行 问题描述 pip install tensorflow报错ERROR: Could not find a version that satisfies the requirement tensorflow (f问题分析 直到在网上看到&#x…

体系结构论文导读(四十五):Design and Dynamic Update of Real-Time Systems 19‘RTSS

挑战部分 背景问题&#xff1a; 现代工业系统和产品&#xff08;如汽车、智能手机、医疗设备&#xff09;越来越依赖于软件&#xff0c;尤其是嵌入式实时系统。这些系统的可靠性对于社会至关重要&#xff0c;比如特斯拉自动驾驶系统的软件问题曾引发一些事故。目前&#xff0c;…