springboot 多数据源配置

1.引入相关pom文件

  <!-- spring boot 启动 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId><exclusions><exclusion><artifactId>log4j-api</artifactId><groupId>org.apache.logging.log4j</groupId></exclusion><exclusion><artifactId>log4j-to-slf4j</artifactId><groupId>org.apache.logging.log4j</groupId></exclusion></exclusions></dependency><!-- mysql驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!-- druid 官方 starter --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.22</version></dependency><!-- mybatis-plus --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><exclusions><exclusion><artifactId>jsqlparser</artifactId><groupId>com.github.jsqlparser</groupId></exclusion></exclusions></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId></dependency><dependency><groupId>com.github.yulichang</groupId><artifactId>mybatis-plus-join</artifactId><version>${mybatis-plus-join.version}</version></dependency><!-- mybatis的分页插件 --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><exclusions><exclusion><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId></exclusion></exclusions></dependency>
<!-- 测试框架 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><exclusions><exclusion><artifactId>junit</artifactId><groupId>junit</groupId></exclusion></exclusions></dependency>

2.配置yml文件

#配置
spring:jackson:default-property-inclusion: non_nullcloud:nacos:discovery:server-addr: ${tc.nacos.server-addr}namespace: ${tc.nacos.namespace}enabled: trueregister-enabled: trueephemeral: true#分析型数据库dorisdatasource:dynamic:primary: db1db1:jdbc-url: jdbc:mysql://127.0.0.1:3306/mb_data_blend?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=falseusername: testpassword: 123456driver-class-name:  com.mysql.cj.jdbc.Driverdb2:jdbc-url: jdbc:mysql://127.0.0.1:3307/mbdb?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=falseusername: testpassword: 123456driver-class-name:  com.mysql.cj.jdbc.Driverdruid:initial-size: 5min-idle: 10max-active: 20max-wait: 60000mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:banner: falsedb-config:logic-delete-value: 1logic-not-delete-value: 0#logic-delete-field: isDeletedmapper-locations: mapper/db1mapper/*.xml,mapper/db2mapper/*.xml

3.创建不同数据源的配置文件

 3.1启动类

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableAsync;import java.text.SimpleDateFormat;
import java.util.Date;@Slf4j
@EnableCaching
@SpringBootApplication(scanBasePackages="com.tc.mb")
@EnableDiscoveryClient
@MapperScan("com.tc.mb.mapper")
@EnableAsync
public class MbDataBlendApplication {public static void main(String[] args) {SpringApplication.run(MbDataBlendApplication.class, args);log.info(new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss]").format(new Date()) + " mb-data-blend service server started!");}}

3.2配置文件

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
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.ApplicationContext;
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;
import java.util.function.Consumer;/*** @Author: LinJun* @Date: 2023/3/3 10:13* @Description:数据源1*/
@Configuration
@MapperScan(basePackages="com.tc.mb.mapper.db1mapper",sqlSessionFactoryRef = "db1SqlSessionFactory")
public class Db1DataSourceConfig {static final String MAPPER_LOCATION = "classpath:/mapper/db1mapper/*.xml";private final ApplicationContext applicationContext;public Db1DataSourceConfig(ApplicationContext applicationContext) {this.applicationContext = applicationContext;}@Primary@Bean(name = "db1DataSource")@ConfigurationProperties(prefix = "spring.datasource.db1")public DataSource dataSource() {return DataSourceBuilder.create().build();}//主数据源 maindb@Primary@Bean("db1SqlSessionFactory")public SqlSessionFactory ds1SqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource, MybatisPlusInterceptor interceptor) throws Exception {MybatisSqlSessionFactoryBean sqlSessionFactory = new MybatisSqlSessionFactoryBean();sqlSessionFactory.setDataSource(dataSource);sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));sqlSessionFactory.setPlugins(interceptor);GlobalConfig globalConfig = GlobalConfigUtils.defaults();this.getBeanThen(MetaObjectHandler.class, globalConfig::setMetaObjectHandler);this.getBeanThen(ISqlInjector.class, globalConfig::setSqlInjector);this.getBeanThen(IdentifierGenerator.class, globalConfig::setIdentifierGenerator);sqlSessionFactory.setGlobalConfig(globalConfig);return sqlSessionFactory.getObject();}private <T> void getBeanThen(Class<T> clazz, Consumer<T> consumer) {if (applicationContext.getBeanNamesForType(clazz, false, false).length > 0) {consumer.accept(applicationContext.getBean(clazz));}}@Primary@Bean(name = "db1TransactionManager")public DataSourceTransactionManager ds1TransactionManager(@Qualifier("db1DataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Primary@Bean(name = "db1SqlSessionTemplate")public SqlSessionTemplate ds1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {return new SqlSessionTemplate(sqlSessionFactory);}
}

另外一个配置类,只是替换所有的db1为db2即可

而且实体类文件夹目录以及xml文件夹目录要和配置里面对应好,其他的就可以根据mybatisplus自动生成代码来了,运行时就会动态的加载切换不同的数据库源

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

(Linux)查看端口占用并关闭进程

1、查看端口占用 netstat -anp |grep 端口号 → 列出所有端口-a或--all&#xff1a;显示所有连线中的Socket&#xff1b;-n: 显示数字地址-p: 显示程序的PID和名称 netstat -tunlp |grep 3306 → 端口号netstat -tunlp |grep mysql → 进程名称netstat -tunlp |grep 29520 →…

智能照明控制系统在体育场馆项目中的应用

摘要&#xff1a;在智能化时代&#xff0c;运用智能技术设计照明已经成为社会发展的关键组成。文章简单介绍了智能体育场馆的含义&#xff0c;然后围绕智能照明系统的基本要求&#xff0c;从灯具选型、灯具配光的光线选择与瞄准、灯具眩光与外溢光控制&#xff1b;基本控制方式…

Windows下 创建 FTP 服务器及相关设置

Windows 创建 FTP 服务器 1. 示例功能说明 FTP 服务器根路径下的目录&#xff1a; C:\USERS\SQQIAN\DESKTOP\FTP └─localuser├─FTP1 # 只有用户名为FTP1可以访问&#xff0c;读写均可│ FTP11.txt│├─FTP2 # 只有用户名为FTP2…

【MongoDB实战】数据备份与恢复(部分迁移)

场景&#xff1a; 需求&#xff1a; 解决方案&#xff1a; 步骤&#xff1a; Stage 1&#xff1a;【生产环境】修改备份文件映射 Stage 2&#xff1a;【生产环境】重新构建mongodb Stage 3&#xff1a;【客户环境】修改备份文件映射&#xff0c;同 Stage 1 Stage 4&…

RPC分布式网络通信框架(二)—— moduo网络解析

文章目录 一、框架通信原理二、框架初始化框架初始化 三、调用端&#xff08;客户端&#xff09;调用端框架调用端主程序 四、提供端&#xff08;服务器&#xff09;提供端主程序提供端框架NotifyService方法Run方法muduo库的优点网络代码RpcProvider::OnConnection业务代码Rpc…

Nature Neuroscience:慢波、纺锤波和涟波耦合如何协调人类睡眠期间的神经元加工和通信

摘要 学习和可塑性依赖于休息期间神经元回路的微调调节。一个尚未解决的难题是&#xff0c;在没有外部刺激或有意识努力的情况下&#xff0c;睡眠中的大脑如何协调神经元的放电率(FRs)以及神经回路内外的通信&#xff0c;以支持突触和系统巩固。利用颅内脑电图对人类海马体和周…

如何把caj文件改成PDF格式?分享三个免费的方法!

在学术研究中&#xff0c;我们可能会遇到CAJ文件&#xff0c;这是一种在中国学术界广泛使用的文档格式。然而&#xff0c;与PDF文件相比&#xff0c;CAJ文件的查看和分享并不那么便捷。下面&#xff0c;我会为你介绍三种免费且简便的方法&#xff0c;帮助你将CAJ文件转化为PDF格…

使用3DS Max 创建未来派螺栓枪模型

推荐&#xff1a; NSDT场景编辑器助你快速搭建可二次开发的3D应用场景 步骤 1 创建一个框并将其转换为可编辑多边形&#xff08;右键单击>转换为&#xff1a;>转换为可编辑多边形&#xff09;&#xff0c;然后使用连接添加一系列边循环&#xff0c;如下图所示。 步骤 2 …

【深度学习笔记】梯度消失与梯度爆炸

本专栏是网易云课堂人工智能课程《神经网络与深度学习》的学习笔记&#xff0c;视频由网易云课堂与 deeplearning.ai 联合出品&#xff0c;主讲人是吴恩达 Andrew Ng 教授。感兴趣的网友可以观看网易云课堂的视频进行深入学习&#xff0c;视频的链接如下&#xff1a; 神经网络和…

udx大带宽大延迟网络与xquic bbr, tcp bbr实测比较

quic在其白皮书中声称可以在大延迟大带宽网络中表现良好&#xff0c;为此我对比过目前xq,lsq,pq几种实现&#xff0c;因为这些都是开源项目通过不断的折腾&#xff0c;向这方面研究的同学索取不同版本的实现进行实际测试。 经过&#xff0c;对不同国家的主机&#xff0c;到国内…

Meta分析在生态环境领域里的应用

Meta分析&#xff08;Meta Analysis&#xff09;是当今比较流行的综合具有同一主题的多个独立研究的统计学方法&#xff0c;是较高一级逻辑形式上的定量文献综述。20世纪90年代后&#xff0c;Meta分析被引入生态环境领域的研究&#xff0c;并得到高度的重视和长足的发展&#x…

东方通信基于 KubeSphere 的云计算落地经验

作者&#xff1a;周峰 吴昌泰 公司简介 东方通信股份有限公司&#xff08;以下简称“东方通信”&#xff09;创立于 1958 年&#xff0c;是一家集硬件设备、软件、服务为一体的整体解决方案提供商。公司于 1996 年成功改制上市&#xff0c;成为上海证交所同时发行 A 股和 B 股…