当前位置: 首页 > news >正文

基于SpringBoot+Druid实现多数据源:注解+编程式

前言

本博客姊妹篇

  • 基于SpringBoot+Druid实现多数据源:原生注解式
  • 基于SpringBoot+Druid实现多数据源:注解+编程式
  • 基于SpringBoot+Druid实现多数据源:baomidou多数据源

一、功能描述

  • 配置方式:配置文件中配置默认数据源,使用数据库存储其他数据源配置
  • 使用方式:使用注解切换数据源,编程式切换数据源

二、代码实现

2.1 配置

# spring配置
spring:# 数据源配置datasource:type: com.alibaba.druid.pool.DruidDataSourcedruid:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/boot_codegen?useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&useSSL=falseusername: rootpassword: rootinitial-size: 10min-idle: 10max-active: 100max-wait: 60000time-between-eviction-runs-millis: 60000min-evictable-idle-time-millis: 300000validation-query: select 1test-while-idle: truetest-on-borrow: falsetest-on-return: falsepool-prepared-statements: truemax-pool-prepared-statement-per-connection-size: 20web-stat-filter:enabled: trueurl-pattern: /*exclusions: '*.js,*.css,*.gif,*.png,*.jpg,*.ico,/druid/*'stat-view-servlet:enabled: trueurl-pattern: /druid/*login-username: adminlogin-password: 123456filter:stat:enabled: truelog-slow-sql: trueslow-sql-millis: 1000merge-sql: truewall:enabled: trueconfig:multi-statement-allow: true

2.2 配置类

package com.qiangesoft.datasourcepro.core;import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;/*** 多数据源配置** @author qiangesoft* @date 2024-03-14*/
@Slf4j
@Configuration
public class DataSourceConfiguration {@Beanpublic DruidDataSource defaultDataSource() {return DruidDataSourceBuilder.create().build();}@Bean@Primarypublic DynamicDataSource dynamicDataSource(DruidDataSource defaultDataSource) {Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put("default", defaultDataSource);return new DynamicDataSource(defaultDataSource, targetDataSources);}
}

2.3 多数据源扩展实现

package com.qiangesoft.datasourcepro.core;import com.alibaba.druid.pool.DruidDataSource;
import com.qiangesoft.datasourcepro.entity.BcgDataSource;
import com.qiangesoft.datasourcepro.service.IBcgDataSourceService;
import com.qiangesoft.datasourcepro.utils.SpringUtil;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import java.util.Map;/*** 动态数据源** @author qiangesoft* @date 2024-03-14*/
public class DynamicDataSource extends AbstractRoutingDataSource {private Map<Object, Object> dynamicTargetDataSources;private Object dynamicDefaultTargetDataSource;public DynamicDataSource(DruidDataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {super.setDefaultTargetDataSource(defaultTargetDataSource);super.setTargetDataSources(targetDataSources);super.afterPropertiesSet();this.dynamicTargetDataSources = targetDataSources;this.dynamicDefaultTargetDataSource = defaultTargetDataSource;}@Overrideprotected Object determineCurrentLookupKey() {String datasourceId = DataSourceContext.getDataSource();if (datasourceId != null && this.dynamicTargetDataSources.containsKey(datasourceId)) {return datasourceId;}return null;}/*** 添加数据源** @param dataSourceId*/public void addDataSource(String dataSourceId) {if ("default".equals(dataSourceId)) {return;}int initialSize = ((DruidDataSource) dynamicDefaultTargetDataSource).getInitialSize();BcgDataSource bcgDataSource = SpringUtil.getBean(IBcgDataSourceService.class).getById(Long.valueOf(dataSourceId));if (bcgDataSource == null) {throw new RuntimeException("数据源配置不存在");}String datasourceId = String.valueOf(bcgDataSource.getId());Map<Object, Object> dynamicTargetDataSources = this.dynamicTargetDataSources;if (!dynamicTargetDataSources.containsKey(datasourceId)) {DruidDataSource dataSourceInstance = DataSourceBuilder.create().driverClassName(bcgDataSource.getDriverClassName()).url(bcgDataSource.getUrl()).username(bcgDataSource.getUsername()).password(bcgDataSource.getPassword()).type(DruidDataSource.class).build();dynamicTargetDataSources.put(datasourceId, dataSourceInstance);// 关键一步:将TargetDataSources中的连接信息放入resolvedDataSources管理super.afterPropertiesSet();}}
}

2.4 切面

package com.qiangesoft.datasourcepro.core;import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;import java.util.Objects;/*** 多数据源处理** @author qiangesoft* @date 2024-03-14*/
@Slf4j
@Order(1)
@Aspect
@Component
public class DataSourceAspect {/*** 切点*/@Pointcut("@annotation(com.qiangesoft.datasourcepro.core.DataSource)")public void pointCut() {}/*** 通知** @param joinPoint* @return* @throws Throwable*/@Around("pointCut()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {DataSource dataSource = this.getDataSource(joinPoint);if (dataSource == null) {DataSourceContext.setDataSource("default");} else {DataSourceContext.setDataSource(dataSource.value());}try {return joinPoint.proceed();} finally {DataSourceContext.removeDataSource();}}/*** 获取数据源** @param joinPoint* @return*/public DataSource getDataSource(ProceedingJoinPoint joinPoint) {MethodSignature signature = (MethodSignature) joinPoint.getSignature();// 方法上查找注解DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);if (Objects.nonNull(dataSource)) {return dataSource;}// 类上查找注解return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);}
}

2.5 线程本地变量

package com.qiangesoft.datasourcepro.core;import com.qiangesoft.datasourcepro.utils.SpringUtil;/*** 数据源上下文** @author qiangesoft* @date 2024-03-14*/
public class DataSourceContext {/*** 线程本地变量:数据源*/private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();/*** 设置数据源的变量*/public static void setDataSource(String dataSourceId) {SpringUtil.getBean(DynamicDataSource.class).addDataSource(dataSourceId);CONTEXT_HOLDER.set(dataSourceId);}/*** 获得数据源的变量*/public static String getDataSource() {return CONTEXT_HOLDER.get();}/*** 清空数据源变量*/public static void removeDataSource() {CONTEXT_HOLDER.remove();}
}

2.6 使用

package com.qiangesoft.datasourcepro.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiangesoft.datasourcepro.core.DataSource;
import com.qiangesoft.datasourcepro.core.DataSourceContext;
import com.qiangesoft.datasourcepro.entity.BcgDataSource;
import com.qiangesoft.datasourcepro.mapper.BcgDataSourceMapper;
import com.qiangesoft.datasourcepro.service.IBcgDataSourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;import java.util.List;/*** <p>* 数据源 服务实现类* </p>** @author qiangesoft* @since 2024-03-13*/
@Slf4j
@RequiredArgsConstructor
@Service
public class BcgBcgDataSourceServiceImpl extends ServiceImpl<BcgDataSourceMapper, BcgDataSource> implements IBcgDataSourceService {@Overridepublic List<BcgDataSource> changeDataSource(String datasourceId) {try {DataSourceContext.setDataSource(datasourceId);return this.list();} catch (Exception e) {e.printStackTrace();throw new RuntimeException("数据源切换失败");} finally {DataSourceContext.removeDataSource();}}@DataSource(value = "1")@Overridepublic List<BcgDataSource> changeDataSourceByAnnotation() {return this.list();}
}

相关文章:

基于SpringBoot+Druid实现多数据源:注解+编程式

前言 本博客姊妹篇 基于SpringBootDruid实现多数据源&#xff1a;原生注解式基于SpringBootDruid实现多数据源&#xff1a;注解编程式基于SpringBootDruid实现多数据源&#xff1a;baomidou多数据源 一、功能描述 配置方式&#xff1a;配置文件中配置默认数据源&#xff0c…...

已解决org.apache.zookeeper.KeeperException.BadVersionException异常的正确解冲方法,亲测有效!!!

已解决org.apache.zookeeper.KeeperException.BadVersionException异常的正确解冲方法&#xff0c;亲测有效&#xff01;&#xff01;&#xff01; 目录 问题分析 报错原因 解决思路 解决方法 总结 博主v&#xff1a;XiaoMing_Java 问题分析 在使用Apache ZooKeeper进行…...

数据结构:堆

堆的概念 1.堆是一个完全二叉树 2.小堆(任何一个父亲<孩子),大堆(任何一个父亲>孩子) 堆的结构 物理结构:数组 逻辑结构:二叉树 #pragma once #include<assert.h> #include<iostream> typedef int HPDataType; typedef struct Heap {HPDataType* _a;int…...

CSS中三栏布局的实现

三栏布局一般指的是页面中一共有三栏&#xff0c;左右两栏宽度固定&#xff0c;中间自适应的布局&#xff0c;三栏布局的具体实现&#xff1a; 利用绝对定位&#xff0c;左右两栏设置为绝对定位&#xff0c;中间设置对应方向大小的margin的值。 .outer {position: relative;h…...

Linux搭建我的世界(MC)整合包服务器,All the Mods 9(ATM9)整合包开服教程

Linux使用MCSM面板搭建我的世界(Minecraft)整合包服务器&#xff0c;MC开服教程&#xff0c;All the Mods 9(ATM9)整合包搭建服务器的教程。 本教程使用Docker来运行mc服&#xff0c;可以方便切换不同Java版本&#xff0c;方便安装多个mc服版本。 视频教程&#xff1a;https:…...

让数据在业务间高效流转,镜舟科技与NineData完成产品兼容互认

近日&#xff0c;镜舟科技与NineData完成产品兼容测试。在经过联合测试后&#xff0c;镜舟科技旗下产品与NineData云原生智能数据管理平台完全兼容&#xff0c;整体运行高效稳定。 镜舟科技致力于帮助中国企业构建卓越的数据分析系统&#xff0c;打造独具竞争力的“数据护城河”…...

2.1HTML5基本结构

HTML5实际上不算是一种编程语言&#xff0c;而是一种标记语言。HTML5文件是由一系列成对出现的元素标签嵌套组合而成&#xff0c;这些标签以<元素名>的形式出现&#xff0c;用于标记文本内容的含义。浏览器通过元素标签解析文本内容并将结果显示在网页上&#xff0c;而元…...

设置浏览器显示小于12px以下字体

问题 我们在项目开发过程中有时候会遇到设计师给的小于12px的字体&#xff0c;IE、火狐浏览器、移动端等小于12px的字号大小还是可以正常显示的&#xff0c;但是谷歌浏览器上显示字体最小为12px&#xff0c;css设置font-size&#xff1a;10px&#xff0c;运行代码显示结果仍然…...

web蓝桥杯真题:成语学习

代码&#xff1a; //TODO 点击文字后&#xff0c;在idiom从左到右第一个空的位置加上改文字 getSingleWord(val) {let index this.idiom.indexOf() //从左往右查询空字符串this.$set(this.idiom, index, val) //响应式更新 },// TODO 校验成语是否输入正确答案 confirm…...

外包干了5天,技术明显退步。。。。。

先说一下自己的情况&#xff0c;本科生&#xff0c;19年通过校招进入南京某软件公司&#xff0c;干了接近2年的功能测试&#xff0c;今年年初&#xff0c;感觉自己不能够在这样下去了&#xff0c;长时间呆在一个舒适的环境会让一个人堕落!而我已经在一个企业干了2年的功能测试&…...

Vue:自定义消息通知组件

一、效果描述 在JS中使用一个Message函数&#xff0c;弹出一个自定义的消息框。 效果体验&#xff1a;缓若江海凝清光 二、实现方式 1.新建一个消息组件 2.新建一个js文件&#xff0c;新建一个需要导出函数 3.在函数中新建一个Vue实例&#xff0c;并将消息组件挂载上去。…...

2023 收入最高的十大编程语言

本期共享的是 —— 地球上目前已知超过 200 种可用的编程语言&#xff0c;了解哪些语言在 2023 为开发者提供更高的薪水至关重要。 过去一年里&#xff0c;我分析了来自地球各地超过 1000 万个开发职位空缺&#xff0c;辅助我们了解市场&#xff0c;以及人气最高和收入最高的语…...

Github 2024-03-11 开源项目周报 Top15

根据Github Trendings的统计&#xff0c;本周(2024-03-11统计)共有15个项目上榜。根据开发语言中项目的数量&#xff0c;汇总情况如下&#xff1a; 开发语言项目数量Python项目4TypeScript项目3Jupyter Notebook项目3C#项目1HTML项目1CSS项目1Dart项目1Lua项目1Shell项目1Rust…...

【DAY10 软考中级备考笔记】数据结构 图

数据结构 图 3月11日 – 天气&#xff1a;晴 晚上无线网络突然不能用了&#xff0c;花费好久弄这个&#xff0c;耽误了一些时间 1. 图的定义 这里需要注意完全图的定义&#xff0c;以及完全图的边数 这里需要注意连通图和连通分量的概念。 2. 图的存储结构 图有两种存储结构&a…...

java-ssm-jsp基于java的餐厅点餐系统的设计与实现

java-ssm-jsp基于java的餐厅点餐系统的设计与实现 获取源码——》公主号&#xff1a;计算机专业毕设大全...

蓝桥杯(1):python排序

1 基础 1.1 输出 1.1.1 去掉输出的空格 print("Hello","World",123,sep"") print("hello",world,123,sep) print(hello,world,123) #输出结果 #HelloWorld123 #helloworld123 #hello world 123 1.1.2 以不同的方式结尾 print(&quo…...

SpringMVC请求、响应和拦截器的使用

SpringMVC请求 RequestMapping注解 RequestMapping注解的作用是建立请求URL和处理方法之间的对应关系 RequestMapping注解可以作用在方法和类上 1. 作用在类上&#xff1a;第一级的访问目录 2. 作用在方法上&#xff1a;第二级的访问目录 3. 细节&#xff1a;路径可以不编写…...

基于springboot+layui仓库管理系统设计和实现

基于 java springbootlayui仓库管理系统设计和实现 博主介绍&#xff1a;多年java开发经验&#xff0c;专注Java开发、定制、远程、文档编写指导等,csdn特邀作者、专注于Java技术领域 作者主页 央顺技术团队 Java毕设项目精品实战案例《1000套》 欢迎点赞 收藏 ⭐留言 文末获取…...

【开源-土拨鼠充电系统】鸿蒙 HarmonyOS 4.0+微信小程序+云平台

本人自己开发的开源项目&#xff1a;土拨鼠充电系统 ✍GitHub开源项目地址&#x1f449;&#xff1a;https://github.com/cheinlu/groundhog-charging-system ✍Gitee开源项目地址&#x1f449;&#xff1a;https://gitee.com/cheinlu/groundhog-charging-system ✨踩坑不易&am…...

[抽象]工厂模式([Abstract] Factory)——创建型模式

[抽象]工厂模式——创建型模式 什么是抽象工厂&#xff1f; 抽象工厂模式是一种创建型设计模式&#xff0c;让你能够保证在客户端程序中创建一系列有依赖的对象组时&#xff0c;无需关心这些对象的类型。 具体来说&#xff1a; 对象的创建与使用分离&#xff1a; 抽象工厂模…...

19c补丁后oracle属主变化,导致不能识别磁盘组

补丁后服务器重启&#xff0c;数据库再次无法启动 ORA01017: invalid username/password; logon denied Oracle 19c 在打上 19.23 或以上补丁版本后&#xff0c;存在与用户组权限相关的问题。具体表现为&#xff0c;Oracle 实例的运行用户&#xff08;oracle&#xff09;和集…...

376. Wiggle Subsequence

376. Wiggle Subsequence 代码 class Solution { public:int wiggleMaxLength(vector<int>& nums) {int n nums.size();int res 1;int prediff 0;int curdiff 0;for(int i 0;i < n-1;i){curdiff nums[i1] - nums[i];if( (prediff > 0 && curdif…...

【ROS】Nav2源码之nav2_behavior_tree-行为树节点列表

1、行为树节点分类 在 Nav2(Navigation2)的行为树框架中,行为树节点插件按照功能分为 Action(动作节点)、Condition(条件节点)、Control(控制节点) 和 Decorator(装饰节点) 四类。 1.1 动作节点 Action 执行具体的机器人操作或任务,直接与硬件、传感器或外部系统…...

React19源码系列之 事件插件系统

事件类别 事件类型 定义 文档 Event Event 接口表示在 EventTarget 上出现的事件。 Event - Web API | MDN UIEvent UIEvent 接口表示简单的用户界面事件。 UIEvent - Web API | MDN KeyboardEvent KeyboardEvent 对象描述了用户与键盘的交互。 KeyboardEvent - Web…...

使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装

以下是基于 vant-ui&#xff08;适配 Vue2 版本 &#xff09;实现截图中照片上传预览、删除功能&#xff0c;并封装成可复用组件的完整代码&#xff0c;包含样式和逻辑实现&#xff0c;可直接在 Vue2 项目中使用&#xff1a; 1. 封装的图片上传组件 ImageUploader.vue <te…...

【配置 YOLOX 用于按目录分类的图片数据集】

现在的图标点选越来越多&#xff0c;如何一步解决&#xff0c;采用 YOLOX 目标检测模式则可以轻松解决 要在 YOLOX 中使用按目录分类的图片数据集&#xff08;每个目录代表一个类别&#xff0c;目录下是该类别的所有图片&#xff09;&#xff0c;你需要进行以下配置步骤&#x…...

MySQL 8.0 OCP 英文题库解析(十三)

Oracle 为庆祝 MySQL 30 周年&#xff0c;截止到 2025.07.31 之前。所有人均可以免费考取原价245美元的MySQL OCP 认证。 从今天开始&#xff0c;将英文题库免费公布出来&#xff0c;并进行解析&#xff0c;帮助大家在一个月之内轻松通过OCP认证。 本期公布试题111~120 试题1…...

根据万维钢·精英日课6的内容,使用AI(2025)可以参考以下方法:

根据万维钢精英日课6的内容&#xff0c;使用AI&#xff08;2025&#xff09;可以参考以下方法&#xff1a; 四个洞见 模型已经比人聪明&#xff1a;以ChatGPT o3为代表的AI非常强大&#xff0c;能运用高级理论解释道理、引用最新学术论文&#xff0c;生成对顶尖科学家都有用的…...

Linux 内存管理实战精讲:核心原理与面试常考点全解析

Linux 内存管理实战精讲&#xff1a;核心原理与面试常考点全解析 Linux 内核内存管理是系统设计中最复杂但也最核心的模块之一。它不仅支撑着虚拟内存机制、物理内存分配、进程隔离与资源复用&#xff0c;还直接决定系统运行的性能与稳定性。无论你是嵌入式开发者、内核调试工…...

CppCon 2015 学习:Time Programming Fundamentals

Civil Time 公历时间 特点&#xff1a; 共 6 个字段&#xff1a; Year&#xff08;年&#xff09;Month&#xff08;月&#xff09;Day&#xff08;日&#xff09;Hour&#xff08;小时&#xff09;Minute&#xff08;分钟&#xff09;Second&#xff08;秒&#xff09; 表示…...