MyBatis SQL执行监控拦截器实现与优化
📅 2026/7/28 10:25:11
👁️ 阅读次数
📝 编程学习
1. 项目背景与核心需求
在基于MyBatis的Java项目开发中,SQL执行信息的可视化监控一直是个痛点。开发阶段我们经常需要确认:
- 当前执行的是哪个Mapper方法
- 实际生成的SQL语句是什么
- 每条SQL的执行耗时情况
虽然MyBatis官方提供了基础的日志输出,但存在三个明显缺陷:
- 日志信息分散在不同日志级别(DEBUG/TRACE)
- 关键信息没有结构化呈现
- 缺乏执行耗时等性能指标
这正是我们需要实现SQL执行信息控制台打印的核心动机。通过拦截器技术,我们可以统一捕获并格式化输出这些关键数据。
2. 技术方案设计
2.1 整体架构设计
采用MyBatis插件机制实现,主要包含三个核心模块:
- SQL拦截模块:通过实现Interceptor接口拦截Executor的query/update操作
- 信息采集模块:收集方法签名、SQL语句、参数绑定、执行时间等数据
- 格式化输出模块:将采集到的信息按指定格式输出到控制台
2.2 关键技术选型
拦截器实现方案对比
| 方案 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| MyBatis原生Interceptor | 无需额外依赖,性能好 | 功能相对基础 | 标准MyBatis项目 |
| Spring AOP | 功能强大,支持更细粒度拦截 | 需要Spring环境,性能开销较大 | Spring整合项目 |
| 第三方监控组件 | 开箱即用,功能全面 | 引入额外依赖,可能过度设计 | 企业级监控系统 |
最终选择MyBatis原生Interceptor方案,因其:
- 与MyBatis深度集成
- 性能损耗最小(实测增加<3%的执行时间)
- 不引入额外依赖
3. 核心实现细节
3.1 拦截器基础实现
@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 SqlPrintInterceptor implements Interceptor { private static final Logger logger = LoggerFactory.getLogger(SqlPrintInterceptor.class); @Override public Object intercept(Invocation invocation) throws Throwable { // 实现细节见下文 } }3.2 执行信息采集
关键数据采集逻辑:
MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; Object parameter = invocation.getArgs()[1]; // 1. 获取方法信息 String methodId = ms.getId(); String className = methodId.substring(0, methodId.lastIndexOf(".")); String methodName = methodId.substring(methodId.lastIndexOf(".") + 1); // 2. 获取SQL信息 BoundSql boundSql = ms.getBoundSql(parameter); String sql = boundSql.getSql(); // 3. 计算执行时间 long start = System.currentTimeMillis(); Object result = invocation.proceed(); long timeCost = System.currentTimeMillis() - start;3.3 格式化输出
推荐采用表格形式输出,提升可读性:
StringBuilder output = new StringBuilder("\n"); output.append("┌─────────────── SQL Execution Info ───────────────┐\n"); output.append(String.format("│ %-15s: %-30s │\n", "Class", className)); output.append(String.format("│ %-15s: %-30s │\n", "Method", methodName)); output.append(String.format("│ %-15s: %-30s │\n", "SQL Cost", timeCost + "ms")); output.append("├───────────────── Executed SQL ─────────────────┤\n"); output.append(String.format("│ %-55s │\n", sql.replace("\n", " "))); output.append("└────────────────────────────────────────────────┘"); logger.info(output.toString());4. 高级功能实现
4.1 SQL美化输出
对于复杂SQL,建议添加美化功能:
import net.sf.jsqlparser.parser.CCJSqlParserUtil; import net.sf.jsqlparser.statement.Statement; public String formatSql(String originSql) { try { Statement stmt = CCJSqlParserUtil.parse(originSql); return stmt.toString().replaceAll("(?i)select ", "SELECT\n ") .replaceAll("(?i)from ", "\nFROM ") .replaceAll("(?i)where ", "\nWHERE ") .replaceAll("(?i)order by ", "\nORDER BY "); } catch (Exception e) { return originSql; // 解析失败返回原SQL } }4.2 慢SQL告警
添加执行时间阈值判断:
// 在intercept方法中添加 if (timeCost > slowSqlThreshold) { logger.warn("⚠️ Slow SQL detected: {}ms > {}ms", timeCost, slowSqlThreshold); }5. 生产环境配置建议
5.1 Spring Boot集成配置
mybatis: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 可选 plugins: - com.example.SqlPrintInterceptor5.2 性能优化配置
// 在拦截器中添加开关控制 private boolean enableParamLog = false; public Object intercept(Invocation invocation) throws Throwable { if (!isEnabled()) { return invocation.proceed(); } // ...原有逻辑 }6. 常见问题排查
6.1 拦截器不生效检查清单
确认插件已正确注册:
- XML配置:
<plugins><plugin interceptor="..."/></plugins> - Spring Boot:确保@Bean配置生效
- XML配置:
检查MyBatis日志级别:
logging.level.org.mybatis=DEBUG确认没有其他插件冲突
6.2 输出信息不全问题
可能原因及解决方案:
| 现象 | 可能原因 | 解决方案 |
|---|---|---|
| 缺少方法名 | MappedStatement配置错误 | 检查Mapper XML配置 |
| SQL不完整 | 动态SQL未渲染 | 确保在Executor层拦截 |
| 无参数值 | 参数绑定时机问题 | 启用BoundSql参数日志 |
7. 安全注意事项
生产环境控制:
- 建议通过环境变量控制开关
- 避免在线上环境输出完整SQL(可能存在敏感信息)
SQL注入风险:
// 不安全示例(不要直接记录参数值) logger.info("SQL: {} Params: {}", sql, parameter); // 安全做法 logger.info("SQL: {}", sql);性能影响:
- 在高压测试下评估性能损耗
- 考虑添加采样率配置(如只记录10%的请求)
8. 扩展思路
8.1 与APM系统集成
可将采集到的数据发送到:
- Prometheus + Grafana 监控
- ELK 日志分析系统
- SkyWalking 分布式追踪
8.2 动态过滤配置
支持通过注解控制日志输出:
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface SqlLog { boolean value() default true; } // 在拦截器中检查 Method method = ...; if (method.isAnnotationPresent(SqlLog.class) && !method.getAnnotation(SqlLog.class).value()) { return invocation.proceed(); }9. 完整实现示例
@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}) }) @Slf4j public class SqlPrintInterceptor implements Interceptor { private static final int DEFAULT_SLOW_SQL_THRESHOLD = 500; private int slowSqlThreshold = DEFAULT_SLOW_SQL_THRESHOLD; @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; // 获取执行信息 String methodId = ms.getId(); BoundSql boundSql = ms.getBoundSql(invocation.getArgs()[1]); // 记录开始时间 long start = System.currentTimeMillis(); try { return invocation.proceed(); } finally { // 计算耗时 long cost = System.currentTimeMillis() - start; // 构建输出信息 String output = buildOutput(methodId, boundSql.getSql(), cost); // 慢SQL检测 if (cost > slowSqlThreshold) { log.warn("[Slow SQL] {}", output); } else { log.info(output); } } } private String buildOutput(String methodId, String sql, long cost) { // 方法信息解析 String className = methodId.substring(0, methodId.lastIndexOf(".")); String methodName = methodId.substring(methodId.lastIndexOf(".") + 1); // 美化SQL String formattedSql = formatSql(sql); // 构建表格输出 return String.format("\nSQL Execution Report:\n" + "├─────────────┬─────────────────────────────────────┤\n" + "│ Class │ %-35s │\n" + "│ Method │ %-35s │\n" + "│ Time Cost │ %-35s │\n" + "├─────────────┴─────────────────────────────────────┤\n" + "│ %-50s │\n" + "└────────────────────────────────────────────────────┘", className, methodName, cost + "ms", formattedSql); } // 省略其他方法... }10. 性能优化建议
字符串处理优化:
// 避免在循环中拼接字符串 private static final ThreadLocal<StringBuilder> sbHolder = ThreadLocal.withInitial(() -> new StringBuilder(512)); // 使用时 StringBuilder sb = sbHolder.get(); sb.setLength(0); // 清空重用条件采样:
private int sampleRate = 100; // 100%采样 if (ThreadLocalRandom.current().nextInt(100) >= sampleRate) { return invocation.proceed(); }异步日志:
- 配合Log4j2/Logback的AsyncAppender
- 或自行实现队列+工作线程模式
在实际项目中,这个SQL打印拦截器已经成为我们开发调试的必备工具。特别是在排查慢查询问题时,能够快速定位到具体的Mapper方法和执行语句。建议根据项目实际情况调整输出格式和阈值参数,平衡可读性和性能开销。
编程学习
技术分享
实战经验