springboot集成mybaits打印sql执行时间

该博客介绍了如何在MyBatis中使用拦截器来监控SQL执行时间,并详细展示了如何配置拦截器以输出执行时间和美化后的SQL语句。拦截器实现了对StatementHandler的query、update和batch方法的拦截,记录了执行耗时,并对SQL进行格式化,以便于日志分析和性能优化。

1. 配置拦截器

import java.lang.reflect.Field;
import java.sql.Statement;
import java.util.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.defaults.DefaultSqlSession.StrictMap;
import org.apache.log4j.Logger;

/**
 * @author: 
 * @date: 2021-08-20 17:56
 * @description: 输出执行时间
 */
@Intercepts(value = {
   
   
        @Signature(args = {
   
    Statement.class, ResultHandler.class }, method = "query", type = StatementHandler.class),
        @Signature(args = {
   
    Statement.class }, method = "update", type = StatementHandler.class),
        @Signature(args = {
   
    Statement.class }, method = "batch", type = StatementHandler.class) })
public class SqlCostInterceptor implements Interceptor{
   
   

    private final Logger logger = Logger.getLogger(SqlCostInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
   
   
        Object target = invocation.getTarget();
        long startTime = System.currentTimeMillis();
        StatementHandler statementHandler = (StatementHandler) target;
        try {
   
   
            return invocation.proceed();
        } finally {
   
   
            long endTime = System.currentTimeMillis();
            long sqlCost = endTime - startTime;
            BoundSql boundSql = statementHandler.getBoundSql();
            String sql = boundSql.getSql();
            Object parameterObject = boundSql.getParameterObject();
            List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();

            // 格式化Sql语句,去除换行符,替换参数
            sql = formatSql(sql, parameterObject, parameterMappingList);
            logger.info("时间:[" + DateUtil.format(new Date(endTime), "yyyy-MM-dd HH:mm:ss.SSS")
                    + 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值