Mybatis插件使用-统计sql执行时间
背景介绍:最近由于产品数据量较大,sql执行十分低效,正在做数据库优化,所以想在日志中看到每个sql执行的时间,以方便针对性的优化。
查找相关资料,了解到Mybatis有一款插件,是基于interceptor来实现的,可以在拦截器中来输出每个sql的执行时间,配置方便且简单,经过自测可用。
1、在dao的配置文件中,在sqlSessionFactory配置项里添加插件依赖:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml" />
<property name="mapperLocations" value="classpath:/sqlmap/*Mapper.xml" />
<property name="dataSource" ref="dataSource" />
<property name="plugins">
<array>
<!-- 基于拦截器的实现,配置拦截器所在工程的全路径 -->
<bean id="sqlStatementInterceptor" class="com.**.interceptor.SqlStatementInterceptor"/>
</array>
</property>
</bean>
2、在工程com.**.interceptor包路径下添加SqlStatementInterceptor.java,具体代码如下:
/**
* Mybatis SQL拦截器,记录每个sqlId对应的执行时间
*
* @author yehaixiao
* @date 2017-09-07
*/
@Intercepts(value = {
@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 }),
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class }) })
public class SqlStatementInterceptor implements Interceptor {
private static Logger logger = Logger.getLogger(SqlStatementInterceptor.class); @Override
public Object intercept(Invocation invocation) {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
// sqlId为mapper文件中定义的id,例如:com.**.dao.**Mapper.selectByPrimaryKey
String sqlId = mappedStatement.getId();
// 开始时间
long start = System.currentTimeMillis();
try {
return invocation.proceed();
} catch (Exception e) {
logger.error(sqlId + "执行失败!", e);
return null;
} finally {
long end = System.currentTimeMillis();
long time = end - start;
StringBuilder str = new StringBuilder();
str.append(sqlId);
str.append(": ");
str.append("cost time ");
str.append(time);
str.append(" ms.");
String sqlInfo = str.toString();
logger.debug(sqlInfo);
}
} @Override
public Object plugin(Object arg0) {
return Plugin.wrap(arg0, this);
} @Override
public void setProperties(Properties arg0) { }
}
说明:自定义的拦截器实现了org.apache.ibatis.plugin.Interceptor,Interceptor中有三个方法:
public abstract interface Interceptor {
public abstract Object intercept(Invocation paramInvocation) throws Throwable;
public abstract Object plugin(Object paramObject);
public abstract void setProperties(Properties paramProperties);
}
我们主要实现了intercept方法,入参是一个Invocation,Invocation的内部结构如下所示:
第一个参数是长度为4的args数组,数组的第一个参数是一个MappedStatement,其实这个就是执行一个sql对应的对象,该对象中有个getId,获取到的结果就是mapper文件中sql定义的id,这样就很容易明白自定义的拦截器里intercept方法里第一句话含义。
直到现在,相关的配置、代码以及说明全都结束,在执行sql的时候,日志中可以看到如下输出: 
Mybatis插件使用-统计sql执行时间的更多相关文章
- Mybatis插件Plugin
Mybatis开源Plugin中最熟知的pagehelper,重点made in China 很多人开始用pagehelper时候,肯定很纳闷,以mysql为例,明明没有加limit语句,为什么打印出 ...
- MyBatis7:MyBatis插件及示例----打印每条SQL语句及其执行时间
Plugins 摘一段来自MyBatis官方文档的文字. MyBatis允许你在某一点拦截已映射语句执行的调用.默认情况下,MyBatis允许使用插件来拦截方法调用 Executor(update.q ...
- MyBatis 插件 : 打印 SQL 及其执行时间
Plugins 摘一段来自MyBatis官方文档的文字. MyBatis允许你在某一点拦截已映射语句执行的调用.默认情况下,MyBatis允许使用插件来拦截方法调用: Executor(update. ...
- MyBatis插件及示例----打印每条SQL语句及其执行时间
Plugins 摘一段来自MyBatis官方文档的文字. MyBatis允许你在某一点拦截已映射语句执行的调用.默认情况下,MyBatis允许使用插件来拦截方法调用 Executor(update.q ...
- Mybatis插件,能做的事情真的很多
大家好,我是架构摆渡人.这是实践经验系列的第九篇文章,这个系列会给大家分享很多在实际工作中有用的经验,如果有收获,还请分享给更多的朋友. Mybatis是我们经常用的一款操作数据库的框架,它的插件机制 ...
- 统计sql语句执行效率
--统计sql语句执行效率SELECT (total_elapsed_time / execution_count)/1000 N'平均时间ms' ,total_elapsed_time/1000 N ...
- Mybatis插件机制以及PageHelper插件的原理
首先现在已经有很多Mybatis源码分析的文章,之所以重复造轮子,只是为了督促自己更好的理解源码. 1.先看一段PageHelper拦截器的配置,在mybatis的配置文件<configurat ...
- 动手实践Mybatis插件
前言 Mybatis的插件开发过程的前提是必须要对Mybatis整个SQL执行过程十分熟悉,这样才能正确覆盖源码保证插件运行,总的来说Mybatis的插件式一种侵入式插件,使用时应该十分注意. 在之前 ...
- mybatis插件机制
目录 mybatis插件机制 主要 类/接口 和 方法 mybatis插件机制实现 mybatis插件机制 mybatis的插件机制使用动态代理实现,不了解的朋友请先了解代理模式和动态代理:插件本质是 ...
随机推荐
- 冲刺博客NO.3
今天做了什么:参考网上的一些登录界面,发现了Android studio自带loginActivity.做了基础登录界面 不停地上网搜,各种不会. 在短信验证功能上通过在Mob.com的集成文档和官 ...
- 编程中常用的DOS命令
1. dir directory 无参数:查看当前所在目录的文件和文件夹. /s : 查看当前目录以及其所有子目录的文件和文件夹 /a :查看包含的隐含文件的所有文件. /ah :只显示出隐含文 ...
- [require-js]向下滑动ajax加载的javascript实现
define(function(){ function ScrollMoreInfo($wraper , loadDataFunc , json_ids , perNum , tpl_info) { ...
- spring mvc 的请求流程
SpringMVC核心处理流程: 1.DispatcherServlet前端控制器接收发过来的请求,交给HandlerMapping处理器映射器 2.HandlerMapping处理器映射器,根据请求 ...
- 经过实际验证的C#调用Haskell的方法
[系统环境] Windows Server 2008 R2,Haskell Platform 2013.2.0.0,ghc 7.6.3,cabal 1.16.0 [操作步骤] 1. 安装Windows ...
- js gettext
test.php 1 <?php $locale='zh_CN'; if(isSet($_GET["locale"]))$locale = $_GET["local ...
- MacOS统计TCP/UDP端口号与对应服务
1.TCP端口 echo "### TCP LISTEN ###" lsof -nP -iTCP -sTCP:LISTEN 2.UDP端口 echo "### UDP L ...
- OCP 062大量考试新题(2019年)-12
12. Your database is configured in archivelog mode. Examine the RMAN configuration parameters: CONFI ...
- 05_python_字典
一.字典定义 字典是python中唯一的映射类型,以{ }括起来的键值对组成,在dict中key是唯一的.在保存时,根据key来计算一个内存地址,然后把key-value保存至地址中.这种算法是has ...
- jQuery基础(2)
一.jQuery的属性操作 jQuery的属性操作分为四部分: html标签属性操作:是对html文档中的标签属性进行读取,设置和移除操作.比如attr().removeAttr(): DOM属性操作 ...