拦截sql执行时间并打印

import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Component;

import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 *
 * @author : ws
 * @date : 2021/4/21 19:32
 * DESCRIPTION:
 */
@Slf4j
@Intercepts({
        @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}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Component
public class SqlExecuteTimeCountInterceptor implements Interceptor {

    /**
     * 执行sql时间超过这个时间,提示异常
     */
    private static long LIMIT_TIME = 500;

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    /**
     * 拦截执行器的方法处理
     *
     * @param invocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        long start = System.currentTimeMillis();
        Object result = invocation.proceed();
        long end = System.currentTimeMillis();
        long executionTime = end - start;
        if (LIMIT_TIME < executionTime) {
            String sql = mappedStatement.getBoundSql(invocation.getArgs().length > 1 ? invocation.getArgs()[1] : null).getSql();
            log.error("执行SQL方法:[{}] 耗时:[{}ms] \nSQL:[" + sql + "]  \n参数:[{}]", mappedStatement.getId(), executionTime, invocation.getArgs().length > 1 ? invocation.getArgs()[1] : "");
        }
        return result;
    }
}

// 在mybatis-config.xml中配置

/**
<configuration>
    <plugins>
        <plugin interceptor="com.xq.mgxq.api.interceptor.SqlExecuteTimeCountInterceptor"/>
    </plugins>
</configuration>
*/

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值