SpringBoot整合P6Spy实现全链路SQL监控

一、p6spy核心作用
  1. 完整SQL捕获:输出带实际参数的SQL语句,无需手动拼接

  2. 性能分析:精确记录每条SQL执行耗时

  3. 慢查询检测:支持阈值配置自动标记慢SQL(如 >2s)

  4. ORM调试:验证MyBatis等框架生成的SQL

二、集成步骤
  1. 添加依赖(关键依赖):

    复制代码
    <dependency>
        <groupId>p6spy</groupId>
        <artifactId>p6spy</artifactId>
        <version>3.9.1</version>
    </dependency>
    <!-- MyBatis Plus需额外添加 -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-p6spy</artifactId>
    </dependency>
  2. 配置数据源(关键改动):

    复制代码
    spring:
      datasource:
        driver-class-name: com.p6spy.engine.spy.P6SpyDriver # 替换驱动
        url: jdbc:p6spy:mysql://localhost:3306/db # URL添加p6spy前缀
  3. 创建日志格式化类(可选增强):

    复制代码
    public class CustomP6SpyLogger implements MessageFormattingStrategy {
        @Override
        public String formatMessage(...) {
            // 示例:添加ANSI颜色/格式化日期参数
            return String.format("\u001B[33m%s | 耗时:%dms | SQL:\u001B[32m%s\u001B[0m", 
                                 now, elapsed, formattedSql);
        }
    }
  4. 配置spy.properties(核心配置):

    复制代码
    # 日志输出方式
    appender=com.p6spy.engine.spy.appender.StdoutLogger
    # 自定义格式化类
    logMessageFormat=com.example.CustomP6SpyLogger
    # 慢SQL检测(2秒阈值)
    outagedetection=true
    outagedetectioninterval=2
    # 排除无关日志
    excludecategories=info,debug,resultset
三、注意事项
  1. 版本兼容:MySQL 8.x需使用p6spy 3.9.x

  2. 性能损耗 :增加约5%-10%开销,生产环境建议:

    • 关闭常规监控

    • 仅启用慢查询检测

  3. 文件位置spy.properties必须放在src/main/resources

  4. 日志优化 :通过excludecategories过滤非SQL日志

四、效果演示

控制台输出示例:

复制代码
2023-05-01 12:30:45 | 耗时: 148ms | SQL: SELECT * FROM user WHERE create_time > '2023-01-01 00:00:00'

可直接拷贝SQL到数据库客户端执行

五、总结

p6spy解决了开发中的两大痛点:

  1. 直观获取完整SQL:摆脱参数占位符拼接

  2. 精准定位慢查询:通过耗时监控优化数据库性能 建议在开发/测试环境启用,生产环境按需使用慢查询监控功能。

相关推荐
做个文艺程序员几秒前
第02篇:搭建 ES 集群 + Spring Boot 整合实战——从 Docker Compose 到 Java 客户端全覆盖
java·spring boot·elasticsearch
无风听海13 分钟前
ASP.NET Core Minimal API 深度解析
后端·asp.net
斯特凡今天也很帅21 分钟前
Spring Boot+mybatis项目切换sql为传参成无参
spring boot·sql·mybatis
IT_陈寒23 分钟前
Java的finally块竟然不是你想的那个finally!
前端·人工智能·后端
weelinking28 分钟前
【claude】15_Claude使用经验与最佳实践
前端·人工智能·python·sql·数据挖掘·前端框架·github
zb2006412034 分钟前
Laravel4.x核心特性全解析
spring boot·后端·php·laravel
Devin~Y1 小时前
大厂Java面试实录:Spring Boot微服务 + Redis缓存 + Kafka消息队列 + Prometheus链路追踪 + RAG向量检索
java·spring boot·redis·spring cloud·kafka·rabbitmq·spring mvc
techdashen1 小时前
在 Async Rust 中实现请求合并(Request Coalescing)
开发语言·后端·rust
lzp07911 小时前
C#如何优雅处理引用类型的深拷贝(贰)
spring boot·后端·ui
阿坤带你走近大数据1 小时前
HiveSQL常见性能调优策略与经验
hive·sql·调优