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

SpringBoot 项目配置动态数据源

目录

    • 一、前言
    • 二、操作
      • 1、引入依赖
      • 2、配置默认数据库 1
      • 3、定义数据源实体和 Repository
      • 4、定义动态数据源
      • 5、配置数据源
      • 6、定义切换数据源注解
      • 7、定义切面类
      • 8、使用注解切换数据源

一、前言

通过切面注解方式根据不同业务动态切换数据库

二、操作

1、引入依赖

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId></dependency>
</dependencies>

2、配置默认数据库 1

  • 在 application.properties 或 application.yml 配置数据库 1 信息:
spring.datasource.url=jdbc:mysql://localhost:3306/db1
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3、定义数据源实体和 Repository

  • 数据源实体 DataSourceConfig.java:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;@Entity
public class DataSourceEntity {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String url;private String username;private String password;private String driverClassName;private String dataSourceKey; // 新增字段// Getters 和 Setterspublic Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUrl() {return url;}public void setUrl(String url) {this.url = url;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getDriverClassName() {return driverClassName;}public void setDriverClassName(String driverClassName) {this.driverClassName = driverClassName;}public String getDataSourceKey() {return dataSourceKey;}public void setDataSourceKey(String dataSourceKey) {this.dataSourceKey = dataSourceKey;}
}
  • Repository 接口 DataSourceConfigRepository.java:
import org.springframework.data.jpa.repository.JpaRepository;public interface DataSourceConfigRepository extends JpaRepository<DataSourceEntity, Long> {
}

4、定义动态数据源

  • 动态数据源上下文持有者 DynamicDataSourceContextHolder.java:
public class DynamicDataSourceContextHolder {private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();public static void setDataSourceKey(String key) {contextHolder.set(key);}public static String getDataSourceKey() {return contextHolder.get();}public static void clearDataSourceKey() {contextHolder.remove();}
}
  • 动态数据源类 DynamicDataSource.java:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DynamicDataSource extends AbstractRoutingDataSource {@Overrideprotected Object determineCurrentLookupKey() {return DynamicDataSourceContextHolder.getDataSourceKey();}
}

5、配置数据源

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Configuration
public class DataSourceConfig {@Autowiredprivate DataSourceConfigRepository dataSourceConfigRepository;@Primary@Beanpublic DataSource dataSource() {DynamicDataSource dynamicDataSource = new DynamicDataSource();Map<Object, Object> targetDataSources = new HashMap<>();// 从数据库 1 的 datasource 表加载所有数据源List<DataSourceEntity> dataSourceConfigs = dataSourceConfigRepository.findAll();for (DataSourceEntity config : dataSourceConfigs) {HikariDataSource dataSource = new HikariDataSource();dataSource.setJdbcUrl(config.getUrl());dataSource.setUsername(config.getUsername());dataSource.setPassword(config.getPassword());dataSource.setDriverClassName(config.getDriverClassName());targetDataSources.put(config.getId().toString(), dataSource);if ("db1".equals(config.getDataSourceKey())) { // 假设表中有一个字段表示数据源的 keydynamicDataSource.setDefaultTargetDataSource(dataSource);}}dynamicDataSource.setTargetDataSources(targetDataSources);return dynamicDataSource;}
}

6、定义切换数据源注解

import java.lang.annotation.*;@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSourceSwitch {String value() default "db1";
}

7、定义切面类

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;import java.lang.reflect.Method;
import java.util.List;@Aspect
@Component
public class DataSourceSwitchAspect {@Autowiredprivate DataSourceConfigRepository dataSourceConfigRepository;@Before("@annotation(com.example.annotation.DataSourceSwitch)")public void before(JoinPoint point) {MethodSignature signature = (MethodSignature) point.getSignature();Method method = signature.getMethod();DataSourceSwitch dataSourceSwitch = method.getAnnotation(DataSourceSwitch.class);if (dataSourceSwitch != null) {String dataSourceKey = dataSourceSwitch.value();List<DataSourceEntity> dataSourceConfigs = dataSourceConfigRepository.findAll();for (DataSourceConfig config : dataSourceConfigs) {if (dataSourceKey.equals(config.getDataSourceKey())) {DynamicDataSourceContextHolder.setDataSourceKey(config.getId().toString());break;}}}}@After("@annotation(com.example.annotation.DataSourceSwitch)")public void after(JoinPoint point) {DynamicDataSourceContextHolder.clearDataSourceKey();}
}

8、使用注解切换数据源

import com.example.annotation.DataSourceSwitch;
import com.example.entity.User;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class UserService {@Autowiredprivate UserRepository userRepository;@DataSourceSwitch("db1")public List<User> getUsersFromDb1() {return userRepository.findAll();}@DataSourceSwitch("db2") // 假设 db2 是从 datasource 表获取的数据源 keypublic List<User> getUsersFromDb2() {return userRepository.findAll();}
}

相关文章:

SpringBoot 项目配置动态数据源

目录 一、前言二、操作1、引入依赖2、配置默认数据库 13、定义数据源实体和 Repository4、定义动态数据源5、配置数据源6、定义切换数据源注解7、定义切面类8、使用注解切换数据源 一、前言 通过切面注解方式根据不同业务动态切换数据库 二、操作 1、引入依赖 <dependen…...

CSS基本选择器

1. 通配选择器 作用&#xff1a;可以选中所有的 HTML 元素。 语法&#xff1a; * { 属性名: 属性值; } 举例&#xff1a; <!DOCTYPE html> <html lang"zh-cn"> <head><meta charset"UTF-8"><meta name"viewport" …...

idea-代码补全快捷键

文章目录 前言idea-代码补全快捷键1. 基本补全2. 类型匹配补全3. 后缀补全4. 代码补全 前言 如果您觉得有用的话&#xff0c;记得给博主点个赞&#xff0c;评论&#xff0c;收藏一键三连啊&#xff0c;写作不易啊^ _ ^。   而且听说点赞的人每天的运气都不会太差&#xff0c;…...

基于SpringBoot+vue粮油商城小程序系统

粮油商城小程序为用户提供方便快捷的在线购物体验&#xff0c;包括大米、面粉、食用油、调味品等各种粮油产品的选购&#xff0c;用户可以浏览商品详情、对比价格、下单支付等操作。同时&#xff0c;商城还提供优惠活动、积分兑换等福利&#xff0c;让用户享受到更多实惠和便利…...

挪车小程序挪车二维码php+uniapp

一款基于FastAdminThinkPHP开发的匿名通知车主挪车微信小程序&#xff0c;采用匿名通话的方式&#xff0c;用户只能在有效期内拨打车主电话&#xff0c;过期失效&#xff0c;从而保护车主和用户隐私。提供微信小程序端和服务端源码&#xff0c;支持私有化部署。 更新日志 V1.0…...

企业内部知识库:安全协作打造企业智慧运营基石

内容概要 作为企业智慧运营的核心载体&#xff0c;企业内部知识库通过结构化的信息聚合与动态化的知识流动&#xff0c;为组织提供了从数据沉淀到价值转化的系统性框架。其底层架构以权限管理为核心&#xff0c;依托数据加密技术构建多层级访问控制机制&#xff0c;确保敏感信…...

网络安全推荐的视频教程 网络安全系列

第一章 网络安全概述 1.2.1 网络安全概念P4 网络安全是指网络系统的硬件、软件及其系统中的数据受到保护&#xff0c;不因偶然的或恶意的原因而遭到破坏、更改、泄露&#xff0c;系统连续可靠正常地运行&#xff0c;网络服务不中断。 1.2.3 网络安全的种类P5 &#xff08;1…...

麒麟管家全新升级,运维问题“一键修复”

麒麟管家是openKylin社区SystemManager SIG开发的一款面向社区用户&#xff0c;能倾听用户烦恼和诉求&#xff0c;也能提供便利途径、解决用户问题的系统管理类应用&#xff0c;可以为用户提供问题反馈、系统垃圾清理、电脑故障排查、硬件设备管理及系统小工具等一站式服务&…...

MVCC(多版本并发控制)机制讲解

MVCC&#xff08;Multi-Version Concurrency Control&#xff0c;多版本并发控制&#xff09;这是一个在数据库管理系统中非常重要的技术&#xff0c;尤其是在处理并发事务时。别担心&#xff0c;我会用简单易懂的方式来讲解&#xff0c;让你轻松掌握它的原理和作用。 1. 什么是…...

React 与 Vue 对比指南 - 上

React 与 Vue 对比指南 - 上 本文将展示如何在 React 和 Vue 中实现常见功能&#xff0c;从基础渲染到高级状态管理 Hello 分别使用 react 和 vue 写一个 Hello World&#xff01; react export default () > {return <div>Hello World!</div>; }vue <…...

开源协议深度解析:理解MIT、GPL、Apache等常见许可证

目录 前言1. MIT协议&#xff1a;自由而宽松的开源许可1.1 MIT协议的主要特点1.2 MIT协议的适用场景 2. GPL协议&#xff1a;自由软件的捍卫者2.1 GPL协议的核心理念2.2 GPL协议的适用场景 3. Apache License 2.0&#xff1a;开源与专利保护的平衡3.1 Apache License 2.0的主要…...

通用评估系统(五)- 前端部分总体说明

通用评估系统&#xff08;五&#xff09;- 前端部分总体说明 相关链接 Gitee地址通用评估系统&#xff08;一&#xff09;- 介绍通用评估系统&#xff08;二&#xff09;- 原型设计通用评估系统&#xff08;三&#xff09;- 前端部分通用评估系统&#xff08;四&#xff09;-…...

STM32GPIO

目录 GPIO基本结构GPIO位结构输入部分输出部分 输出模式GPIO模式浮空/上拉/下拉模拟输入开漏和推挽复用开漏/复用推挽 GPIO基本结构 GPIO是挂载在APB2总线上的外设。GPIO结构中的寄存器分为输入寄存器和输出寄存器&#xff0c;APB2总线通过输出寄存器向引脚发送数据&#xff0c…...

MyBatis拦截器终极指南:从原理到企业级实战

在本篇文章中&#xff0c;我们将深入了解如何编写一个 MyBatis 拦截器&#xff0c;并通过一个示例来展示如何在执行数据库操作&#xff08;如插入或更新&#xff09;时&#xff0c;自动填充某些字段&#xff08;例如 createdBy 和 updatedBy&#xff09;信息。本文将详细讲解拦…...

SpringBoot启动失败之application.yml缩进没写好

修改前&#xff1a; spring前面空格了 报错输出&#xff1a;Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured. Reason: Failed to determine a suitable driver class Action: Consider the follow…...

【JavaScript】《JavaScript高级程序设计 (第4版) 》笔记-Chapter17-事件

十七、事件 事件 JavaScript 与 HTML 的交互是通过事件实现的&#xff0c;事件代表文档或浏览器窗口中某个有意义的时刻。可以使用仅在事件发生时执行的监听器&#xff08;也叫处理程序&#xff09;订阅事件。在传统软件工程领域&#xff0c;这个模型叫“观察者模式”&#xff…...

鸿蒙开发:V2版本装饰器之@Monitor装饰器

前言 本文代码案例基于Api13。 随着官方的迭代&#xff0c;在新的Api中&#xff0c;对于新的应用开发&#xff0c;官方已经建议直接使用V2所属的装饰器进行开发了&#xff0c;所以&#xff0c;能上手V2的尽量上手V2吧&#xff0c;毕竟&#xff0c;V2是V1的增强版本&#xff0c;…...

51单片机-外部中断

以外部中断0为例&#xff1a; 主程序中需要有以下代码&#xff1a; EA1; //打开总中断开关 EX01; //开外部中断0 IT00/1&#xff1b; 设置外部中断的触发方式 P3.2\P3.3为外部中断接口&#xff0c;通过控制P3.2口按键按下实现LED灯反转点亮 #include "reg52.h"typed…...

UE C++ UObject 功能的初步总结(结合官方文档)

一. Uboject的官方文档的个人理解 Objects in Unreal Engine | 虚幻引擎 5.5 文档 | Epic Developer Community 目录在此 1.垃圾回收:上篇文章简单介绍过&#xff0c;UObject的创建和回收。本身是很复杂的功能&#xff0c;后续会接着单项深入分析。 2.引用更新 1. 反射:之前…...

DeepSeek和ChatGPT的全面对比

一、模型基础架构对比&#xff08;2023技术版本&#xff09; 维度DeepSeekChatGPT模型家族LLAMA架构改进GPT-4优化版本参数量级开放7B/35B/120B闭源175B位置编码RoPE NTK扩展ALiBiAttention机制FlashAttention-3FlashAttention-2激活函数SwiGLU ProGeGLU训练框架DeepSpeedMeg…...

Linux链表操作全解析

Linux C语言链表深度解析与实战技巧 一、链表基础概念与内核链表优势1.1 为什么使用链表&#xff1f;1.2 Linux 内核链表与用户态链表的区别 二、内核链表结构与宏解析常用宏/函数 三、内核链表的优点四、用户态链表示例五、双向循环链表在内核中的实现优势5.1 插入效率5.2 安全…...

IGP(Interior Gateway Protocol,内部网关协议)

IGP&#xff08;Interior Gateway Protocol&#xff0c;内部网关协议&#xff09; 是一种用于在一个自治系统&#xff08;AS&#xff09;内部传递路由信息的路由协议&#xff0c;主要用于在一个组织或机构的内部网络中决定数据包的最佳路径。与用于自治系统之间通信的 EGP&…...

Python爬虫实战:研究feedparser库相关技术

1. 引言 1.1 研究背景与意义 在当今信息爆炸的时代,互联网上存在着海量的信息资源。RSS(Really Simple Syndication)作为一种标准化的信息聚合技术,被广泛用于网站内容的发布和订阅。通过 RSS,用户可以方便地获取网站更新的内容,而无需频繁访问各个网站。 然而,互联网…...

连锁超市冷库节能解决方案:如何实现超市降本增效

在连锁超市冷库运营中&#xff0c;高能耗、设备损耗快、人工管理低效等问题长期困扰企业。御控冷库节能解决方案通过智能控制化霜、按需化霜、实时监控、故障诊断、自动预警、远程控制开关六大核心技术&#xff0c;实现年省电费15%-60%&#xff0c;且不改动原有装备、安装快捷、…...

条件运算符

C中的三目运算符&#xff08;也称条件运算符&#xff0c;英文&#xff1a;ternary operator&#xff09;是一种简洁的条件选择语句&#xff0c;语法如下&#xff1a; 条件表达式 ? 表达式1 : 表达式2• 如果“条件表达式”为true&#xff0c;则整个表达式的结果为“表达式1”…...

dedecms 织梦自定义表单留言增加ajax验证码功能

增加ajax功能模块&#xff0c;用户不点击提交按钮&#xff0c;只要输入框失去焦点&#xff0c;就会提前提示验证码是否正确。 一&#xff0c;模板上增加验证码 <input name"vdcode"id"vdcode" placeholder"请输入验证码" type"text&quo…...

鸿蒙中用HarmonyOS SDK应用服务 HarmonyOS5开发一个医院查看报告小程序

一、开发环境准备 ​​工具安装​​&#xff1a; 下载安装DevEco Studio 4.0&#xff08;支持HarmonyOS 5&#xff09;配置HarmonyOS SDK 5.0确保Node.js版本≥14 ​​项目初始化​​&#xff1a; ohpm init harmony/hospital-report-app 二、核心功能模块实现 1. 报告列表…...

论文阅读:LLM4Drive: A Survey of Large Language Models for Autonomous Driving

地址&#xff1a;LLM4Drive: A Survey of Large Language Models for Autonomous Driving 摘要翻译 自动驾驶技术作为推动交通和城市出行变革的催化剂&#xff0c;正从基于规则的系统向数据驱动策略转变。传统的模块化系统受限于级联模块间的累积误差和缺乏灵活性的预设规则。…...

Docker拉取MySQL后数据库连接失败的解决方案

在使用Docker部署MySQL时&#xff0c;拉取并启动容器后&#xff0c;有时可能会遇到数据库连接失败的问题。这种问题可能由多种原因导致&#xff0c;包括配置错误、网络设置问题、权限问题等。本文将分析可能的原因&#xff0c;并提供解决方案。 一、确认MySQL容器的运行状态 …...

华为OD最新机试真题-数组组成的最小数字-OD统一考试(B卷)

题目描述 给定一个整型数组,请从该数组中选择3个元素 组成最小数字并输出 (如果数组长度小于3,则选择数组中所有元素来组成最小数字)。 输入描述 行用半角逗号分割的字符串记录的整型数组,0<数组长度<= 100,0<整数的取值范围<= 10000。 输出描述 由3个元素组成…...