ibatis中SQL查询耗时监控拦截器

1、定义拦截器


@Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
@Slf4j
public class SlowQueryInterceptor implements Interceptor {
    private long queryTimeThreshold;

    // 设置慢查询的时间阈值
    public void setQueryTimeThreshold(long queryTimeThreshold) {
        this.queryTimeThreshold = queryTimeThreshold;
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if (invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        long start = System.currentTimeMillis();
        try {
            return invocation.proceed();
        } finally {
            long end = System.currentTimeMillis();
            long executeTime = end - start;
            if (executeTime > queryTimeThreshold) {
                // 记录慢查询日志
                logSlowQuery(mappedStatement, parameter, executeTime);
            }
        }
    }

    private void logSlowQuery(MappedStatement ms, Object parameter, long time) {
        log.info("-----------------------------------------------------------------");
        log.info("查询耗时:" + time +",SQL: "+ms.getBoundSql(parameter).getSql());
    }

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

}

二、注册拦截器

@Configuration
public class FrameMyBatisPluginConfig {

    //SQL查询耗时时间设置,超过则打印sql
    @Value("${sql.execute.over.time.for.print:4000}")
    private long overTime;

    @Bean
    public String SQLTableNameHandleInterceptor(SqlSessionFactory sqlSessionFactory) {
        //实例化插件
        SlowQueryInterceptor slowQueryInterceptor = new SlowQueryInterceptor();

        //将属性值设置到插件中
        slowQueryInterceptor.setQueryTimeThreshold(overTime);
        //将插件添加到SqlSessionFactory工厂
        sqlSessionFactory.getConfiguration().addInterceptor(slowQueryInterceptor);
        return "interceptor";
    }
}

三、日志效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值