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的插件机制使用动态代理实现,不了解的朋友请先了解代理模式和动态代理:插件本质是 ...
随机推荐
- execl 导出
/** * 导出 是把数表中的数据添加到execl表中 */ public function export(){ $xlsData = Db('user')->select(); Vendo ...
- whu暑期集训#1
题号:SGU123----SGU131 Problem A: 题意:求斐波那契的前N项和.. 做法:直接模拟,注意得用long long Problem B: 题意:给定一个封闭的多边形,求一个点在不 ...
- [php] php - json_encode 函数
json_encode()函数, $arr= array("key"=>null); echo json_encode($arr);{"key":null ...
- jwt身份认证
项目地址:https://github.com/cuongle/WebApi.Jwt
- node-webkit学习(4)Native UI API 之window
node-webkit学习(4)Native UI API 之window 文/玄魂 目录 node-webkit学习(4)Native UI API 之window 前言 4.1 window a ...
- 【BZOJ4827】 [Hnoi2017]礼物
BZOJ4827 [Hnoi2017]礼物 Solution 如果一串数的增加,不就等于另一串数减吗? 那么我们可以把答案写成另一个形式: \(ans=\sum_{i=1}^n(x_i-y_i+C)^ ...
- HTML textares的使用
<textarea>标签定义及用法 在html中,<textarea>标签是用来定义一个多行的文本输入控件,在文本输入域中可以输入任意长度的文本.文本默认字体是等宽字体(Cou ...
- nsurlsessiond - taking up all bandwidth!! Help ?
https://discussions.apple.com/thread/6605949?start=0&tstart=0 #!/bin/sh launchctl unload /System ...
- per学习笔记-zkclient,curator使用
开源客户端,原生api的不足 连接的创建是异步的,需要开发人员自行编码实现等待 连接没有自动的超时重连机制 Zk本身没提供序列化机制,需要开发人员自行指定,从而实现数据的序列化和反序列化 Watche ...
- flask_json数据入库Mongo
首先我们先导入python内置的json库,用来将接送数据转换为python对象 import json #导入自定义的数据公共库 from db_tool import db #载入库之前先清空数据 ...