mybatis通过插件方式实现读写分离
原理:通过自定义mybatis插件,拦截Executor的update和query方法,检查sql中有select就用读的库,其它的用写的库(如果有调用存储过程就另当别论了)
@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 }) })
@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 RWDataSourceMybatisPlugin implements Interceptor {
private static final String REGEX = ".*insert\\u0020.*|.*delete\\u0020.*|.*update\\u0020.*";
private static final Map<String, RWDataSourceType> cacheMap = new ConcurrentHashMap<>();
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] objects = invocation.getArgs();
MappedStatement ms = (MappedStatement) objects[0];
RWDataSourceType dataSourceType = null;
if ((dataSourceType = cacheMap.get(ms.getId())) == null) {
// 读方法
if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) {
// !selectKey 为自增id查询主键(SELECT LAST_INSERT_ID() )方法,使用主库
if (ms.getId().contains(SelectKeyGenerator.SELECT_KEY_SUFFIX)) {
dataSourceType = RWDataSourceType.WRITE;
} else {
BoundSql boundSql = ms.getSqlSource().getBoundSql(objects[1]);
String sql = boundSql.getSql().toLowerCase().replaceAll("[\\t\\n\\r]", " ");
if (sql.matches(REGEX)) {
dataSourceType = RWDataSourceType.WRITE;
} else {
dataSourceType = RWDataSourceType.READ;
}
}
} else {
dataSourceType = RWDataSourceType.WRITE;
}
cacheMap.put(ms.getId(), dataSourceType);
}
// 修改当前线程要选择的数据源的key
RWDataSourceHolder.putDataSource(dataSourceType);
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
}
附:
MyBatis 允许你在已映射语句执行过程中的某一点进行拦截调用。默认情况下,MyBatis 允许使用插件来拦截的方法调用包括:
- Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
- ParameterHandler (getParameterObject, setParameters)
- ResultSetHandler (handleResultSets, handleOutputParameters)
- StatementHandler (prepare, parameterize, batch, update, query)
spring boot加载插件方式
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean fb = new SqlSessionFactoryBean();
fb.setDataSource(dataSource);
fb.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapper-locations")));
PageHelper pageHelper = new PageHelper();
Properties props = new Properties();
props.setProperty("reasonable", "true");
props.setProperty("supportMethodsArguments", "true");
props.setProperty("returnPageInfo", "check");
props.setProperty("params", "count=countSql");
pageHelper.setProperties(props);
fb.setPlugins(new Interceptor[] { pageHelper, new MybatisSqlInterceptor() });
return fb.getObject();
}
随便开发的一个记录sql的插件
package com.qmtt.config; import java.sql.Connection;
import java.util.Properties; import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature; @Intercepts({ @Signature(type = StatementHandler.class, method = "prepare", args = { Connection.class, Integer.class }) })
public class MybatisSqlInterceptor implements Interceptor { @Override
public Object intercept(Invocation invocation) throws Throwable { StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
BoundSql boundSql = statementHandler.getBoundSql();
String sql = boundSql.getSql();
System.out.println(sql);
return invocation.proceed();
} @Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
} @Override
public void setProperties(Properties properties) {
// String dialect = properties.getProperty("dialect");
}
}
mybatis通过插件方式实现读写分离的更多相关文章
- Spring Boot + Mybatis 多数据源配置实现读写分离
本文来自网易云社区 作者:王超 应用场景:项目中有一些报表统计与查询功能,对数据实时性要求不高,因此考虑对报表的统计与查询去操作slave db,减少对master的压力. 根据网上多份资料测试发现总 ...
- SpringMVC4+MyBatis+SQL Server2014实现读写分离
前言 基于mybatis的AbstractRoutingDataSource和Interceptor用拦截器的方式实现读写分离,根据MappedStatement的boundsql,查询sql的sel ...
- 基于Spring和Mybatis拦截器实现数据库操作读写分离
首先需要配置好数据库的主从同步: 上一篇文章中有写到:https://www.cnblogs.com/xuyiqing/p/10647133.html 为什么要进行读写分离呢? 通常的Web应用大多数 ...
- Spring aop应用之实现数据库读写分离
Spring加Mybatis实现MySQL数据库主从读写分离 ,实现的原理是配置了多套数据源,相应的sqlsessionfactory,transactionmanager和事务代理各配置了一套,如果 ...
- 重新学习Mysql数据13:Mysql主从复制,读写分离,分表分库策略与实践
一.MySQL扩展具体的实现方式 随着业务规模的不断扩大,需要选择合适的方案去应对数据规模的增长,以应对逐渐增长的访问压力和数据量. 关于数据库的扩展主要包括:业务拆分.主从复制.读写分离.数据库分库 ...
- SSM/SSH框架的MySQL 读写分离实现的一种简单方法
简介 MySQL已经是使用最为广泛的一种数据库,往往实际使用过程中,为实现高可用及高性能,项目会采用主丛复制的方式实现读写分离.MySQL本身支持复制,通过简单的配置即可实现一主多从的配置,具体实现可 ...
- MHA + Maxscale 数据库的高可用和读写分离
MySQL 常见发行版本 MySQL 标准化.自动化部署 深入浅出MySQL备份与恢复 深入理解MySQL主从复制 MySQL构架设计与容量规划 MHA Maxscale MySQL 常见发行版本 M ...
- 安装oneproxy实现数据库的读写分离
领导就给了两台数据库,做主从,在从上搭建oneproxy插件,实现读写分离,一直就听说oneproxy,今天打算用一下 先下载最新的版本wget http://www.onexsoft.cn/soft ...
- 基于Mycat实现读写分离
随着应用的访问量并发量的增加,应用读写分离是很有必要的.当然应用要实现读写分离,首先数据库层要先做到主从配置,本人前一篇文章介绍了mysql数据库的主从配置方式即:<mysql数据库主从配置&g ...
随机推荐
- 「翻译」Unity中的AssetBundle详解(一)
AssetBundles AssetBundle是一个存档文件,其中包含平台在运行时加载的特定资产(模型,纹理,预制,音频剪辑,甚至整个场景).AssetBundles可以表示彼此之间的依赖关系;例如 ...
- js实现网页多少秒后自动跳转到指定网址
在网上搜了一下,关于这个技术处理有多种方法,我只记下我在视频里学到的三种: 1.用一个response.sendRedirect("目标页面.jsp\.htm");实现直接跳转: ...
- 跳转到AppStore 的不同位置办法
程序跳转到appstore中指定的应用 1.进入appstore中指定的应用NSString *str = [NSString stringWithFormat: ...
- 关闭ext4文件系统的日志功能
最近在帮一个研究生弄一个虚拟化环境下的基于Innodb的日志文件的读写优化的实验,实验的具体详细内容就不说了,其中有一个步骤需要将MySQL的日志文件放置在一块单独的硬盘里面,这块硬盘要么是ext2, ...
- 书写优雅的shell脚本(三) - shell中exec解析
参考:<linux命令.编辑器与shell编程> <unix环境高级编程> exec和source都属于bash内部命令(builtins commands),在bash下输入 ...
- 贪吃蛇小游戏—C++、Opencv编写实现
贪吃蛇游戏,C++.Opencv实现 设计思路: 1.显示初始画面,蛇头box初始位置为中心,食物box位置随机 2.按随机方向移动蛇头,按a.s.d.w键控制移动方向,分别为向左,向下,向右,向上 ...
- setTimeout的第三个参数
最熟悉的地方,往往会忽略一些细节.就比如 setTimeout 函数,做前端开发的同学都会很熟悉这个函数,经常使用这个函数,但是知道这个函数还有第三个参数的小伙伴可能就不多了.起码我在阅读阮老师的 e ...
- 查看JVM运行时堆内存
利用jmap和MAT等工具查看JVM运行时堆内存 https://www.cnblogs.com/cjsblog/p/9561375.html jmap JDK自带了一些工具可以帮助我们查看JVM运行 ...
- HNOI2008 越狱 (组合数学)
传送门 应该是HNOI2008年最简单的一道题了吧……简单的组合数题,不过要换个思路. 我们直接考虑发生越狱的情况似乎有点复杂,那我们换个思路,考虑不发生越狱的情况,也就是两个有相同宗教的人不会坐在一 ...
- jQuery测试结果
您的回答: 1.下面哪种说法是正确的? 您的回答:jQuery 是 JavaScript 库 2.jQuery 使用 CSS 选择器来选取元素? 您的回答:正确 3.jQuery 的简写是? 您的回答 ...