原理:通过自定义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通过插件方式实现读写分离的更多相关文章

  1. Spring Boot + Mybatis 多数据源配置实现读写分离

    本文来自网易云社区 作者:王超 应用场景:项目中有一些报表统计与查询功能,对数据实时性要求不高,因此考虑对报表的统计与查询去操作slave db,减少对master的压力. 根据网上多份资料测试发现总 ...

  2. SpringMVC4+MyBatis+SQL Server2014实现读写分离

    前言 基于mybatis的AbstractRoutingDataSource和Interceptor用拦截器的方式实现读写分离,根据MappedStatement的boundsql,查询sql的sel ...

  3. 基于Spring和Mybatis拦截器实现数据库操作读写分离

    首先需要配置好数据库的主从同步: 上一篇文章中有写到:https://www.cnblogs.com/xuyiqing/p/10647133.html 为什么要进行读写分离呢? 通常的Web应用大多数 ...

  4. Spring aop应用之实现数据库读写分离

    Spring加Mybatis实现MySQL数据库主从读写分离 ,实现的原理是配置了多套数据源,相应的sqlsessionfactory,transactionmanager和事务代理各配置了一套,如果 ...

  5. 重新学习Mysql数据13:Mysql主从复制,读写分离,分表分库策略与实践

    一.MySQL扩展具体的实现方式 随着业务规模的不断扩大,需要选择合适的方案去应对数据规模的增长,以应对逐渐增长的访问压力和数据量. 关于数据库的扩展主要包括:业务拆分.主从复制.读写分离.数据库分库 ...

  6. SSM/SSH框架的MySQL 读写分离实现的一种简单方法

    简介 MySQL已经是使用最为广泛的一种数据库,往往实际使用过程中,为实现高可用及高性能,项目会采用主丛复制的方式实现读写分离.MySQL本身支持复制,通过简单的配置即可实现一主多从的配置,具体实现可 ...

  7. MHA + Maxscale 数据库的高可用和读写分离

    MySQL 常见发行版本 MySQL 标准化.自动化部署 深入浅出MySQL备份与恢复 深入理解MySQL主从复制 MySQL构架设计与容量规划 MHA Maxscale MySQL 常见发行版本 M ...

  8. 安装oneproxy实现数据库的读写分离

    领导就给了两台数据库,做主从,在从上搭建oneproxy插件,实现读写分离,一直就听说oneproxy,今天打算用一下 先下载最新的版本wget http://www.onexsoft.cn/soft ...

  9. 基于Mycat实现读写分离

    随着应用的访问量并发量的增加,应用读写分离是很有必要的.当然应用要实现读写分离,首先数据库层要先做到主从配置,本人前一篇文章介绍了mysql数据库的主从配置方式即:<mysql数据库主从配置&g ...

随机推荐

  1. pyenv 安装本地版本

    最近在用pyenv安装python的时候发现官网特别慢,经常出现拒绝访问的情况.看了一些解决方法,发现可以使用本地的python源码进行安装,让pyenv从本地下载就可以了~步骤如下: 首先从官网下载 ...

  2. oracle 错误代码表

    ORA-00001: 违反唯一约束条件 (.) ORA-00017: 请求会话以设置跟踪事件 ORA-00018: 超出最大会话数 ORA-00019: 超出最大会话许可数 ORA-00020: 超出 ...

  3. Delphi通过POST传递参数给PHP

    Delphi代码 ******************************************************************************************* ...

  4. [SoapUI] Reference parameter 引用变量

    Reference parameter in WADL : Endpoint : ${#Project#DomainServer} Resource : {AdvisorID} Reference p ...

  5. 「LuoguT36048」 Storm in Lover

    Description 平成二十四年(2012年),5月11日,东京,某弓道场. "呐,呐,海未酱,你听说了吗?几天后的那场弓道大会?啊-!"橙发少女兴奋地拿着一张传单一样的纸跑向 ...

  6. PostgreSQ 连接问题 FATAL: no pg_hba.conf entry for host

    PostgreSQ数据库为了安全,它不会监听除本地以外的所有连接请求,当用户通过JDBC访问是,会报一些如下的异常: org.postgresql.util.PSQLException: FATAL: ...

  7. pdf解锁和脱水印

    解锁工具下载http://pan.baidu.com/s/1o8FcKFC 使用方法: 第一步: 打开加密pdf文件保存即可 参考:http://www.epinv.com/post/157.html

  8. Entity Framework 实体间的外键关系

    EF 默认是开户级联删除的,这此规则将会删除非空外键和多对多的关系,如果 在数据库上下文中的实体模型类 存在着 级联引用和多重删除路径,那么EF就抛出 级联引用和多重删除路径的异常. Introduc ...

  9. HDU6035:Colorful Tree(树形DP)

    传送门 题意 给出一棵最小生成树及每个节点的颜色,询问\(\frac{n(n-1)}2\)条路径的权值和,一条路径的权值为该路径的颜色种数 分析 勉强理解了ftae的做法,但是代码还是不太会,还是太弱 ...

  10. hdoj5813【构造】

    2016 Multi-University Training Contest 7 05 真的真的好菜哇... 思路: 暴力. 我对那些到达目的地少的点做硬性规定就是去比他要到达目的地更少的点,这样一来 ...