欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用MyBatis拦截器记录SQL执行时间

程序员文章站 2022-08-26 10:56:08
1、在项目的applicationContext-dao.xml 文件中增加一个plugins:sqlStatementInterceptor

1、在项目的applicationContext-dao.xml 文件中增加一个plugins:sqlStatementInterceptor

<bean id="dao-sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="mapperLocations">
            <list>
                <value>classpath:com/test/mapper/*.xml</value>
                <value>classpath:com/test/mapper/extend/*.xml</value>
            </list>
        </property>
        <property name="plugins">
            <array>
                <bean id="sqlStatementInterceptor" class="com.test.SqlStatementInterceptor"/>
            </array>
        </property>
</bean>

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 = {
        @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 = 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.