当前位置:首页 > Java 框架原理百科 > 正文

MyBatis查Java优学网插件开发:轻松实现SQL性能监控与优化

@Intercepts({

@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})

}) public class SimpleLogPlugin implements Interceptor {

MyBatis查Java优学网插件开发:轻松实现SQL性能监控与优化

@Override
public Object intercept(Invocation invocation) throws Throwable {
    long startTime = System.currentTimeMillis();
    try {
        return invocation.proceed();
    } finally {
        long endTime = System.currentTimeMillis();
        System.out.println("SQL执行耗时:" + (endTime - startTime) + "ms");
    }
}

}

MyBatis查Java优学网插件开发:轻松实现SQL性能监控与优化

@Intercepts({

@Signature(type = Executor.class, method = "query", 
          args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})

}) public class PerformanceMonitorPlugin implements Interceptor {

private static final Logger logger = LoggerFactory.getLogger(PerformanceMonitorPlugin.class);

@Override
public Object intercept(Invocation invocation) throws Throwable {
    MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
    Object parameter = invocation.getArgs()[1];
    
    long startTime = System.currentTimeMillis();
    try {
        Object result = invocation.proceed();
        long endTime = System.currentTimeMillis();
        
        // 记录完整的性能数据
        logPerformanceData(mappedStatement, parameter, endTime - startTime, result);
        return result;
    } catch (Exception e) {
        long endTime = System.currentTimeMillis();
        logger.error("SQL执行失败,耗时:{}ms", endTime - startTime);
        throw e;
    }
}

private void logPerformanceData(MappedStatement mappedStatement, Object parameter, 
                              long costTime, Object result) {
    if (costTime > 1000) { // 超过1秒的查询记录警告
        logger.warn("慢SQL检测 - 执行时间:{}ms, SQL: {}", costTime, 
                   mappedStatement.getBoundSql(parameter).getSql());
    }
    
    // 记录常规性能数据
    logger.info("SQL执行统计 - 时间:{}ms, 方法:{}", 
               costTime, mappedStatement.getId());
}

}

你可能想看:

相关文章:

文章已关闭评论!