mybatis拦截器-统计sql执行耗时

原文链接:https://blog.csdn.net/weixin_39168541/article/details/120268843

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.logging.jdbc.PreparedStatementLogger;
import org.apache.ibatis.logging.jdbc.StatementLogger;
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.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Proxy;
import java.sql.Statement;
import java.util.Properties;

/**
 * @author: wenyong.wang@kuwo.cn
 * @version: v1.0
 * @description: com.memberintergral.musicplayerservice.util
 * @date:2022/9/26
 */
@Component
@Intercepts({ @Signature(method = "query", type = StatementHandler.class, args = {Statement.class, ResultHandler.class}) })
@Slf4j
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
//        Callable<Object> callable = () -> invocation.proceed();
//        Consumer<Long> consumer = takeTime -> printSql(takeTime, invocation);
//        Object proceed = FrameTimer.takeTime(callable, consumer);
//        return proceed;

        FrameTimer frameTimer = FrameTimer.getInstance();
        Long startTime = frameTimer.getSplitTime0();
        Object proceed = invocation.proceed();
        Long endTime = frameTimer.getSplitTime0();
        frameTimer.stop0();
        printSql(endTime - startTime, invocation);
        return proceed;
    }

    public void printSql(Long takeTime, Invocation invocation){
        if (takeTime > 100) {
            //获取查询sql
            String sql = parseSql(invocation);
            //打印日志信息
            log.info("requestId:{}, method:{}, sql exec take time is {}ms", FrameTimer.getUUID(), "intercept", takeTime);
            log.info("sql is : {}", sql);
        }
    }

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

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }

    /**
     * 获得真正的处理对象,可能多层代理.
     */
    public String parseSql(Invocation invocation) {
        String sql="";
        Statement statement=(Statement) invocation.getArgs()[0];
        if(Proxy.isProxyClass(statement.getClass())){
            MetaObject metaObject= SystemMetaObject.forObject(statement);
            Object h=metaObject.getValue("h");
            if(h instanceof StatementLogger){
                RoutingStatementHandler rsh=(RoutingStatementHandler) invocation.getTarget();
                sql=rsh.getBoundSql().getSql();
            }else {
                PreparedStatementLogger psl=(PreparedStatementLogger) h;
                sql=psl.getPreparedStatement().toString();
            }
        }else{
            sql=statement.toString();
        }
        return sql;
    }

}
    @Bean(name = "musicPlaySqlSessionFactory")
    @Primary
    public SqlSessionFactory adminSqlSessionFactory(@Qualifier("musicPlayDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/musicPlayer/*.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/musicPlayer/**/*.xml"));
        bean.setPlugins(new Interceptor[]{new MybatisInterceptor()});
        return bean.getObject();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值