SpringBoot多数据源基于mybatis插件(三)

embedded/2024/9/23 6:21:51/

SpringBoot多数据源基于mybatis插件(三)

  • 1.主要思路
  • 2.具体实现

1.主要思路

MyBatis的插件机制允许你在MyBatis的四大对象(Executor、StatementHandler、ParameterHandler和ResultSetHandler)的方法执行前后进行拦截,并可以在方法执行前后插入自定义逻辑。

这里其实就是利用Exector对象执行多数据操作,通过判断操作的类型来动态选择数据源。

在这里插入图片描述

2.具体实现

以下是一个Springboot整合mybatis案例:

在这里插入图片描述yml文件配置:

spring:datasource:datasource1:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/test_masterusername: rootpassword: rootdruid:initial-size: 1min-idle: 1max-active: 20test-on-borrow: truedatasource2:driver-class-name: com.mysql.cj.jdbc.Driverjdbc-url: jdbc:mysql://localhost:3306/test_slaveusername: rootpassword: rootdruid:initial-size: 1min-idle: 1max-active: 20test-on-borrow: truemybatis:type-aliases-package: com.rql.entitymapper-locations: classpath:mybatis/*.xml
DataSourceConfig.java
@Configuration
public class DataSourceConfig {@Bean@ConfigurationProperties(prefix = "spring.datasource.datasource1")public DataSource dataSource1(){return DataSourceBuilder.create().build();}@Bean@ConfigurationProperties(prefix = "spring.datasource.datasource2")public DataSource dataSource2(){return DataSourceBuilder.create().build();}@Beanpublic Interceptor DynamicDataSourcePlugin(){return new DynamicDataSourcePlugin();}
}
DynamicDataSourcePlugin.java
@Intercepts({@Signature(type = Executor.class,method = "update",args = {MappedStatement.class,Object.class}),@Signature(type = Executor.class,method = "query",args = {MappedStatement.class,Object.class, RowBounds.class,ResultHandler.class})})
public class DynamicDataSourcePlugin implements Interceptor {@Overridepublic Object intercept(Invocation invocation) throws Throwable {//拿到当前方法【update、query】的所有参数Object[] objects = invocation.getArgs();//MappedStatement 封装sqlMappedStatement ms = (MappedStatement) objects[0];//读方法if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {DynamicDataSource.name.set("r");} else {//写方法DynamicDataSource.name.set("w");}return invocation.proceed();}@Overridepublic Object plugin(Object target) {if (target instanceof Executor) {return Plugin.wrap(target, this);} else {return target;}}@Overridepublic void setProperties(Properties properties) {}}
  • @Intercepts注解:

@Intercepts :注解用于指定该插件要拦截的目标方法和参数。
@Signature :注解用于指定要拦截的接口、方法及其参数类型。在这个例子中,插件拦截了 Executor 接口的 updatequery 方法。

  • intercept方法:

这是插件的核心方法,当被拦截的方法被调用时,这个方法会被执行。
通过 Invocation 对象,可以获取到被拦截方法的参数,并可以执行被拦截的方法。
在这里,根据SQL的类型(读或写),使用 DynamicDataSource.name.set() 方法来设置不同的数据源(假设 DynamicDataSource 这里设置为 “r” 代表读数据源,“w” 代表写数据源)。

DynamicDataSource.java
@Component
@Primary
public class DynamicDataSource extends AbstractRoutingDataSource {public static ThreadLocal<String> name=new ThreadLocal<>();@AutowiredDataSource dataSource1;@AutowiredDataSource dataSource2;@Overrideprotected Object determineCurrentLookupKey() {return name.get();}@Overridepublic void afterPropertiesSet() {//targetDataSources初始化数据源HashMap<Object, Object> targetDataSources = new HashMap<>();targetDataSources.put("w", dataSource1);targetDataSources.put("r", dataSource2);super.setTargetDataSources(targetDataSources);//为defaultTargetDataSource设置默认数据源super.setDefaultTargetDataSource(dataSource1);super.afterPropertiesSet();}
}

同时,需要将DynamicDataSourcePlugin 的Bean注入到Spring容器中

    @Beanpublic Interceptor DynamicDataSourcePlugin(){return new DynamicDataSourcePlugin();}

http://www.ppmy.cn/embedded/7277.html

相关文章

使用 Cucumber框架进行BDD测试的一些项目

BehatMage 项目地址: https://github.com/MageTest/BehatMage 不过该项目在GitHub中有超过10年没有更新了。 项目介绍&#xff1a; BehatMage项目介绍 BehatMage是一个基于Behat的Magento测试框架&#xff0c;用于自动化测试Magento电子商务平台的功能和性能。Behat是一个行…

T3BI T3BI RS-232通讯操作指南与培训PPT课件

T3BI T3BI RS-232通讯操作指南与培训PPT课件

数据结构-KMP算法

KMP算法 简单的模式匹配算法 定义:子串的定位操作通常称为串的模式匹配,他求的是子串在主串中的位置过程 逐个字符比较 从主串指针 i 对应的字符和模式串指针 j 对应的字符开始&#xff0c;依次比较它们是否相等。若相等&#xff0c;则同时移动 i 和 j 向右一位&#xff0c;继续…

Springboot集成Ehcache3实现本地缓存

如果只需要在单个应用程序中使用本地缓存&#xff0c;则可以选择Ehcache&#xff1b;它支持内存和磁盘存储&#xff0c;这里不以注解方式演示&#xff0c;通过自己实现缓存管理者灵活控制缓存的读写&#xff1b; 1、引入相关依赖 <!-- ehcache3集成start --><depende…

软件测试的经验和教训

1. 认知心理学是测试的基础。 >>>对事物的认知程度&#xff0c;才能对事物做出评价。对事物没有任何认知和了解&#xff0c;就不会有判断<<< 2. 与测试有关的一些问题&#xff1a; a.人的感觉和记忆可靠性 b.信念从哪里来 c.信念如何影响人的行为 d.做…

封装原生html的table处理方法【参数类似eltable】

直接跑html即可 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>封装原生talbe</title> </…

【贪玩巴斯】Vm/ubantu虚拟机报错04005和70057解决方法如下(基于WindowsX64系统)

&#x1f4da;Vm/ubantu虚拟机报错04005和70057解决方法如下&#xff08;基于WindowsX64系统&#xff09;&#xff1a; 错误1场景描述&#xff1a;04005 返回 代码:E_FAIL (0X80004005)组件:SessionMachine界面:ISession {c0447716-ff5a-4795-b57a-ecd5fffa18a4}打开电脑启动虚…

mapreduce中的ReduceTask工作机制(Hadoop)

ReduceTask 是 Hadoop 中的一个重要组件&#xff0c;负责对 MapTask 的输出进行合并、排序和归并&#xff0c;最终生成最终的输出结果。 ReduceTask 的工作机制 1. 分组&#xff08;Shuffle&#xff09;阶段&#xff1a; 在分组阶段&#xff0c;ReduceTask 会从多个 Mapper …