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

Spring Boot 动态数据源切换

背景

随着互联网应用的快速发展,多数据源的需求日益增多。Spring Boot 以其简洁的配置和强大的功能,成为实现动态数据源切换的理想选择。本文将通过具体的配置和代码示例,详细介绍如何在 Spring Boot 应用中实现动态数据源切换,帮助开发者高效应对不同业务场景下的数据管理需求。无论是读写分离还是数据隔离,都能轻松搞定。

AOP动态代理

AOP注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TargetDataSource {String name();
}

AOP切面类

@Aspect
@Component
public class DataSourceAspect {@Pointcut("@annotation(com.example.aliyunai.db.TargetDataSource)")public void dataSourcePointcut() {}@Before("dataSourcePointcut()")public void changeDataSource(JoinPoint point) {MethodSignature signature = (MethodSignature) point.getSignature();Method method = signature.getMethod();TargetDataSource targetDataSource = method.getAnnotation(TargetDataSource.class);if (targetDataSource != null) {String dataSourceName = targetDataSource.name();DataSourceContextHolder.setDataSourceKey(dataSourceName);}}@After("dataSourcePointcut()")public void clearDataSource(JoinPoint point) {DataSourceContextHolder.clearDataSourceKey();}
}

数据源配置

@Configuration
public class DataSourceConfig {@Bean(name = "master")public DataSource primaryDataSource() {return DataSourceBuilder.create().type(HikariDataSource.class).driverClassName("").url("").username("").password("").build();}@Bean(name = "slave")public DataSource secondaryDataSource() {return DataSourceBuilder.create().type(HikariDataSource.class).driverClassName("").url("").username("").password("").build();}@Bean(name = "dynamicDataSource")@Primarypublic DynamicDataSource dynamicDataSource(@Qualifier("master") DataSource master,@Qualifier("slave") DataSource slave) {Map<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put("master", master);targetDataSources.put("slave", slave);DynamicDataSource dynamicDataSource = new DynamicDataSource();dynamicDataSource.setTargetDataSources(targetDataSources);dynamicDataSource.setDefaultTargetDataSource(master);return dynamicDataSource;}}

线程上下文


public class DataSourceContextHolder {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();}
}

动态数据源设置

public class DynamicDataSource extends AbstractRoutingDataSource {private static final Logger logger = LoggerFactory.getLogger(DynamicDataSource.class);@Overrideprotected Object determineCurrentLookupKey() {String dataSourceKey = DataSourceContextHolder.getDataSourceKey();logger.info("Determining current data source: {}", dataSourceKey);return dataSourceKey;}
}

service类

@Service
public class UserService {@Resourceprivate UserMapper userMapper;@TargetDataSource(name = "master")public User queryFromPrimary() {User user = userMapper.selectById(1);return user;}@TargetDataSource(name = "slave")public User queryFromSecondary() {User user = userMapper.selectById(1L);return user;}
}

Mybatis 拦截器


@Component
@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),@Signature(type = Executor.class, method = "update", args = {MappedStatement.class,Object.class})})
public class DynamicDataSourceInterceptor implements Interceptor {private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceInterceptor.class);// 假设这里有一个获取当前数据源标识的方法,你需要根据实际项目中的实现来替换private String getCurrentDataSourceKey() {// 示例:从某个上下文持有者中获取数据源标识,这里只是示意,实际要替换return DataSourceContextHolder.getDataSourceKey();}@Overridepublic Object intercept(Invocation invocation) throws Throwable {MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];Object parameter = invocation.getArgs()[1];BoundSql boundSql = mappedStatement.getBoundSql(parameter);String sql = boundSql.getSql();//对单个表进行处理logger.info("sql:"+sql);String mappedStatementId = mappedStatement.getId();//对所有查询进行处理if (mappedStatementId.contains("query")) {String table = getTable(sql);if (table.equals("user")){DataSourceContextHolder.setDataSourceKey(getCurrentDataSourceKey());}//增删改}else if (mappedStatementId.contains("update")) {DataSourceContextHolder.setDataSourceKey(getCurrentDataSourceKey());}return invocation.proceed();}@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}private static String getTable(String sql) {// 定义正则表达式模式,用于匹配 "from" 和 "where" 之间的表名Pattern pattern = Pattern.compile("FROM\\s+(\\w+)\\s+WHERE");Matcher matcher = pattern.matcher(sql);if (matcher.find()) {return matcher.group(1);}return null;}
}


http://www.mrgr.cn/news/77961.html

相关文章:

  • 玩转 JMeter:Random Order Controller让测试“乱”出花样
  • 《探秘鸿蒙NEXT中的人工智能核心架构》
  • 【C++/控制台】2048小游戏
  • 基于GAN和RL的思想来训练对话生成
  • 详解Sonar与Jenkins 的集成使用!
  • Ubuntu 磁盘修复
  • 十一、排他思想、window、延时定时器、间歇函数、时间戳、location、navigator、history、本地存储localStorage
  • C++设计模式-享元模式
  • 安装 Docker(使用国内源)
  • 从0开始学PHP面向对象内容之常用设计模式(适配器,桥接,装饰器)
  • 大模型系列11-ray
  • 疑难Tips:NextCloud域名访问登录时卡住,显示违反内容安全策略
  • k8s网络服务
  • C#设计模式——抽象工厂模式(重点)
  • Vue3响应式原理
  • Springboot项目搭建-Maven打包编译
  • 演示如何使用 `nn.CrossEntropyLoss` 来计算交叉熵损失,计算损失值的演示代码,和讲解 ,CrossEntropyLoss 损失数值等于零的原因
  • hugo文章支持数学公式
  • oracle 12c查看执行过的sql及当前正在执行的sql
  • 【计算机网络】多路转接之select
  • 新华三嵌入式面试题及参考答案
  • 海信Java后端开发面试题及参考答案
  • 第三十九篇 ShuffleNet V1、V2模型解析
  • Optional类
  • Leetcode 51 N Queens
  • 高频面试题(含笔试高频算法整理)基本总结回顾16