Springboot-多数据源

文章目录

  • 一、架构
  • 二、实现过程
    • 2.1 第一步:引入依赖pom
    • 2.2 第二步:创建application.yml配置
    • 2.3 第三步:创建架构的文件夹
      • MybatisPlusConfig
      • FirstDataSourceConfig
      • SecondDataSourceConfig

实现功能,在不同的文件夹使用不同的库

一、架构

在这里插入图片描述

二、实现过程

2.1 第一步:引入依赖pom

        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>

        <!-- MySQL Driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <!-- MyBatis Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

添加扫描的xml

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>*.yml</include>
                    <include>**/*.yml</include>
                    <include>**/*.xml</include>
                    <include>**/*.txt</include>
                </includes>
            </resource>
        </resources>

2.2 第二步:创建application.yml配置

在这里插入图片描述

server:
  port: 8082

spring:
  banner:
    location:
      classpath: banner.txt
  datasource:
    first:
      username: root
      password: root
      jdbc-url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
      driver-class-name: com.mysql.cj.jdbc.Driver
    second:
      username: root
      password: root
      jdbc-url: jdbc:mysql://xxx.xxx.xxx.xxx:3306/db?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
      driver-class-name: com.mysql.cj.jdbc.Driver


mybatis-plus:
  configuration:
    # 配置打印日志common/config/FirstDataSourceConfig.java和SecondDataSourceConfig.java也需要改成StdOutImpl
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    log-impl: org.apache.ibatis.logging.log4j2.Log4j2Impl
    map-underscore-to-camel-case: true
    jdbc-type-for-null: 'null'
    cache-enabled: false

  global-config:
    db-config:
      id-type: auto

2.3 第三步:创建架构的文件夹

MybatisPlusConfig

package com.admin.ssb_wav.common.config;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class MybatisPlusConfig {

    /***
     * 分页插件
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}

FirstDataSourceConfig

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Title: FirstDataSourceConfig
 * @Author 代码浪人
 * @Date 2024/9/19 17:14
 * @description:
 */
@Configuration
@MapperScan(basePackages = "基础包的.mapper.first", sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDataSourceConfig {

    @Autowired
    private MybatisPlusConfig mybatisPlusConfig;

    @Bean("firstDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.first")
    public DataSource getFirstDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 使用Mybati-plus自带的方法时时必须使用MybatisSqlSessionFactoryBean,用SqlSessionFactoryBean会报错
     * Invalid bound statement (not found): com.wyc.cloudblog.mapper.cloudblog.CategoryMapper.selectList
     */
    @Bean("firstSqlSessionFactory")
    @Primary
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //添加mybatisplus分页插件,不然分页查询返回值中total为0
        bean.setPlugins(mybatisPlusConfig.paginationInterceptor());
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/first/*.xml"));

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        // 配置打印sql语句,如果不配置,多数据源下不会打印
        //开发控制台打印
        // configuration.setLogImpl(StdOutImpl.class);
        configuration.setLogImpl(Log4j2Impl.class);
        bean.setConfiguration(configuration);

        return bean.getObject();
    }

    @Bean(name = "firstTransactionManager")
    @Primary
    public DataSourceTransactionManager testTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

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

}

SecondDataSourceConfig


import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.log4j2.Log4j2Impl;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Title: SecondDataSourceConfig
 * @Author 代码浪人
 * @Date 2024/9/19 17:14
 * @description:
 */
@Configuration
@MapperScan(basePackages = "基础包的.mapper.second", sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {

    @Autowired
    private MybatisPlusConfig mybatisPlusConfig;

    @Bean("secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource getSecondDataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 使用Mybati-plus自带的方法时时必须使用MybatisSqlSessionFactoryBean,用SqlSessionFactoryBean会报错
     * Invalid bound statement (not found): com.wyc.cloudblog.mapper.cloudblog.CategoryMapper.selectList
     */
    @Bean("secondSqlSessionFactory")
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //添加mybatisplus分页插件,不然分页查询返回值中total为0
        bean.setPlugins(mybatisPlusConfig.paginationInterceptor());
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/second/*.xml"));

        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        // 配置打印sql语句,如果不配置,多数据源下不会打印
        //开发控制台打印
        // configuration.setLogImpl(StdOutImpl.class);
        configuration.setLogImpl(Log4j2Impl.class);
        bean.setConfiguration(configuration);

        return bean.getObject();
    }

    @Bean(name = "secondTransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("secondDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean("secondSqlSessionTemplate")
    public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

基于Hive和Hadoop的电商消费分析系统

本项目是一个基于大数据技术的电商消费分析系统&#xff0c;旨在为用户提供全面的电商消费信息和深入的消费行为分析。系统采用 Hadoop 平台进行大规模数据存储和处理&#xff0c;利用 MapReduce 进行数据分析和处理&#xff0c;通过 Sqoop 实现数据的导入导出&#xff0c;以 S…

Updates were rejected because the tip of your current branch is behind 的解决方法

1. 问题描述 当我们使用 git push 推送代码出现以下问题时&#xff1a; 2. 原因分析 这个错误提示表明当前本地分支落后于远程分支&#xff0c;因此需要先拉取远程的更改。 3. 解决方法 1、拉取远程更改 在终端中执行以下命令&#xff0c;拉取远程分支的更新并合并到本地…

基于Arduino的L298N电机驱动模块使用

一.简介&#xff1a; L298N作为电机驱动芯片&#xff0c;具有驱动能力强&#xff0c;发热量低&#xff0c;抗干扰能力强的特点,一个模块可同时驱动两个直流电机工作&#xff0c;能够控制电机进行正转、反转、PWM调速。 说明&#xff1a; 1&#xff09;12V输入端口接入供电电压…

cpp,git,unity学习

c#中的? 1. 空值类型&#xff08;Nullable Types&#xff09; ? 可以用于值类型&#xff08;例如 int、bool 等&#xff09;&#xff0c;使它们可以接受 null。通常&#xff0c;值类型不能为 null&#xff0c;但是通过 ? 可以表示它们是可空的。 int? number null; // …

数据分析-28-交互式数据分析EDA工具和低代码数据科学工具

文章目录 1 数据分析的七步指南1.1 第一步:问题定义和数据采集1.2 第二步:数据清洗和预处理1.3 第三步:数据探索和分析1.4 第四步:模型建立和分析1.5 第五步:数据可视化1.6 第六步:结果解释和报告1.7 第七步:部署和维护1.8 基础的数据分析库1.9 低代码数据科学工具2 EDA…

Linux网络操作命令与函数全面总结

1. 引言 Linux作为服务器和开发平台&#xff0c;网络操作是其核心功能之一。本文旨在全面总结Linux系统中的网络操作方法&#xff0c;包括命令行工具和编程接口&#xff0c;帮助读者深入理解Linux网络管理的机制。 2. 命令行工具 2.1 ping 命令 ping 命令用于测试网络连接和…

css的背景background属性

CSS的background属性是一个简写属性&#xff0c;它允许你同时设置元素的多个背景相关的子属性。使用这个属性可以简化代码&#xff0c;使其更加清晰和易于维护。background属性可以设置不同的子属性。 background子属性 定义背景颜色 使用background-color属性 格式&#x…

了解Webpack并处理样式文件

目录 引入定义安装和使用配置文件命令配置单独文件指定文件 处理样式css-loader使用 style-loaderless-loaderPostCSSpostcss-loaderpostcss-preset-env 引入 随着前端的快速发展&#xff0c;目前前端的开发已经变的越来越复杂了&#xff1a; 比如开发过程中我们需要通过模块化…

python UNIT 3 选择与循环(2)

目录 1。循环的优化 经典优化分析&#xff1a; 未优化的代码&#xff1a; 细节分析&#xff1a; 优化后的代码&#xff1a; 优化的细节&#xff1a; 性能对比 优化的关键在于&#xff1a; 经典习题讲解&#xff1a;(紫色的解析请重点关注一下) 1。例三 个人代码解析…

Qt网络编程——QTcpServer和QTcpSocket

文章目录 核心APITCP回显服务器TCP回显客户端 核心API QTcpServer用于监听端口和获取客户端连接 名称类型说明对标原生APIlisten(const QHostAddress&, quint16 port)方法绑定指定的地址和端口号&#xff0c;并开始监听bind和listennextPendingConnection()方法从系统中获…

大数据-155 Apache Druid 架构与原理详解 数据存储 索引服务 压缩机制

点一下关注吧&#xff01;&#xff01;&#xff01;非常感谢&#xff01;&#xff01;持续更新&#xff01;&#xff01;&#xff01; 目前已经更新到了&#xff1a; Hadoop&#xff08;已更完&#xff09;HDFS&#xff08;已更完&#xff09;MapReduce&#xff08;已更完&am…

Java-IO模型

所谓I/O就是计算机内存与外部设备之间拷贝数据的过程。由于CPU访问内存的速度远远高于外部设备&#xff0c;因此CPU是先把外部设备的数据读到内存里&#xff0c;然后再进行处理。对于一个网络I/O通信过程&#xff0c;比如网络数据读取&#xff0c;会涉及两个对象&#xff0c;一…

Ubuntu 开机自启动 .py / .sh 脚本,可通过脚本启动 roslaunch/roscore等

前言 项目中要求上电自启动定位程序&#xff0c;所以摸索了一种 Ubuntu 系统下开机自启动的方法&#xff0c;开机自启动 .sh 脚本&#xff0c;加载 ROS 环境的同时启动 .py 脚本。在 . py 脚本中启动一系列 ROS 节点。 一、 .sh 脚本的编写 #!/bin/bash # gnome-terminal -- …

javaWeb,Maven

前端打包的程序放在nginx中 查看哪个程序占用了80端口号 Maven&#xff1a;

rk3399开发环境的介绍

零. 前言 由于Bluez的介绍文档有限&#xff0c;以及对Linux 系统/驱动概念、D-Bus 通信和蓝牙协议都有要求&#xff0c;加上网络上其实没有一个完整的介绍Bluez系列的文档&#xff0c;所以不管是蓝牙初学者还是蓝牙从业人员&#xff0c;都有不小的难度&#xff0c;学习曲线也相…

生产绩效考核管理的六大指标

生产绩效考核管理的六大指标 绩效考核是指生产部所有人员通过不断丰富自己的知识、提高自己的技能、改善自己的工作态度&#xff0c;努力创造良好的工作环境及工作机会&#xff0c;不断提高生产效率、提高产品质量、提高员工士气、降低成本以及保证交期和安全生产的结果和行为…

极狐GitLab 17.4 升级指南

GitLab 是一个全球知名的一体化 DevOps 平台&#xff0c;很多人都通过私有化部署 GitLab 来进行源代码托管。极狐GitLab https://dl.gitlab.cn/6y2wxugm 是 GitLab 在中国的发行版&#xff0c;专门为中国程序员服务。可以一键式部署极狐GitLab。 本文分享极狐GitLab 17.4 升级…

9.24作业

将昨天的My_string类中的所有能重载的运算符全部进行重载 、[] 、>、<、、>、<、! 、&#xff08;可以加等一个字符串&#xff0c;也可以加等一个字符&#xff09;、输入输出(<< 、 >>) 代码如下 MyString.h #ifndef MYSTRING_H #define MYSTRING_…

检查一个CentOS服务器的配置的常用命令

在CentOS系统中&#xff0c;查看服务器配置的常用命令非常丰富&#xff0c;这些命令可以帮助用户快速了解服务器的硬件信息、系统状态以及网络配置等。以下是一些常用的命令及其简要说明&#xff1a; 1. 查看CPU信息 (1) cat /proc/cpuinfo&#xff1a;显示CPU的详细信息&…

react+antdMobie实现消息通知页面样式

一、实现效果 二、代码 import React, { useEffect, useState } from react; import style from ./style/index.less; import { CapsuleTabs, Ellipsis, Empty, SearchBar, Tag } from antd-mobile; //消息通知页面 export default function Notification(props) {const [opti…