用MyBatis拦截器记录SQL执行时间
1、在项目的applicationContext-dao.xml 文件中增加一个plugins:sqlStatementInterceptor
classpath:com/test/mapper/*.xml
classpath:com/test/mapper/extend/*.xml
2、编写sqlStatementInterceptor的实现代码
package com.test;
import java.util.Properties;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 数据库操作性能拦截器,记录耗时
*/
@Intercepts(value = https://www.it610.com/article/{
@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, CacheKey.class, BoundSql.class }),
@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
RowBounds.class, ResultHandler.class }) })
public class SqlStatementInterceptor implements Interceptor
{
private static Logger logger = LoggerFactory.getLogger(SqlStatementInterceptor.class);
private Properties properties;
@Override
public Object intercept(Invocation arg0) throws Throwable
{
MappedStatement mappedStatement = (MappedStatement) arg0.getArgs()[0];
String sqlId = mappedStatement.getId();
Object returnValue;
long start = System.currentTimeMillis();
returnValue = https://www.it610.com/article/arg0.proceed();
long end = System.currentTimeMillis();
long time = end - start;
StringBuilder str = new StringBuilder(100);
str.append(sqlId);
str.append(": ");
str.append("cost time ");
str.append(time);
str.append(" ms.");
String sqlInfo = str.toString();
logger.debug(sqlInfo);
return returnValue;
}@Override
public Object plugin(Object arg0)
{
return Plugin.wrap(arg0, this);
}@Override
public void setProperties(Properties arg0)
{
this.properties = arg0;
}
}
3、对sqlStatementInterceptor.java类里面的输出级别(上面代码块是debug级别),进行相应的logback.xml设置(只需修改文件内的level标签)
4、启动项目,从log文件中可看到日志打印
[http-8080-5] DEBUG [Caller+0 at com.test.SqlStatementInterceptor.intercept(SqlStatementInterceptor.java:49) ] - com.test.testMapper.selectByExample: cost time 1 ms.
参考文章:
【用MyBatis拦截器记录SQL执行时间】https://my.oschina.net/u/2265143/blog/786295
http://blog.csdn.net/tq02h2a/article/details/50772652
推荐阅读
- Docker应用:容器间通信与Mariadb数据库主从复制
- JS中的各种宽高度定义及其应用
- 由浅入深理解AOP
- 【译】20个更有效地使用谷歌搜索的技巧
- 涉毒患者(新诗)
- 参保人员因患病来不及到指定的医疗机构就医,能否报销医疗费用()
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- mybatisplus如何在xml的连表查询中使用queryWrapper
- mybatisplus|mybatisplus where QueryWrapper加括号嵌套查询方式
- MybatisPlus|MybatisPlus LambdaQueryWrapper使用int默认值的坑及解决