不灭的焱

革命尚未成功,同志仍须努力下载JDK17

作者:Albert.Wen  添加时间:2022-05-08 23:45:24  修改时间:2024-04-23 20:01:15  分类:Java框架/系统  编辑

一、引言

在我们日常开发工作当中,避免不了查看当前程序所执行的SQL语句,便于程序员排忧解难呐。

不过,打印SQL只适用于开发环境,不建议生产环境使用

二、性能分析插件

2.1 引入maven依赖

<!-- p6spy Sql性能分析工具-->
<dependency>
    <groupId>p6spy</groupId>
    <artifactId>p6spy</artifactId>
    <version>3.9.1</version>
</dependency>

2.2 修改yml配置

原先的urldriver-class-name修改成p6spy的驱动和url形式。

本质上p6spy相当于代理了jdbc操作

server:
  port: 8088
spring:
  datasource:
    driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    url: jdbc:p6spy:mysql://localhost:3306/mp_high?useSSL=false&serverTimezone=GMT%2B8
#    driver-class-name: com.mysql.cj.jdbc.Driver
#    url: jdbc:mysql://localhost:3306/mp_high?useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: 123456
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true # 开启驼峰命名

2.3 新建配置文件:spy.properties

文件内容:填入jdbc连接的驱动,以及日志输出配置

# 应用的拦截模块
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
#logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
logMessageFormat=com.p6spy.engine.spy.appender.CustomLineFormat
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
driverlist=com.mysql.cj.jdbc.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
# 自定义日志配置
# 可用的变量为:
#   %(connectionId)            connection id
#   %(currentTime)             当前时间
#   %(executionTime)           执行耗时
#   %(category)                执行分组
#   %(effectiveSql)            提交的SQL 换行
#   %(effectiveSqlSingleLine)  提交的SQL 不换行显示
#   %(sql)                     执行的真实SQL语句,已替换占位
#   %(sqlSingleLine)           执行的真实SQL语句,已替换占位 不换行显示
customLogMessageFormat=[%(currentTime)] [%(category)-%(connectionId)] [execute time: %(executionTime) ms] execute sql:\n %(sqlSingleLine)

如果以上配置无法满足你的需求,可以查看一下详细的 spy.properties 说明,根据自己的需求配置。

完成!然后就可以在控制台中查看到执行sql返回数据消耗的时间,例如:

@Autowired
UserMapper userMapper;


@Test
public void selectTest(){
    List<User> users = userMapper.selectList(null);
    System.out.println(users);
}

然后就可以根据sql的执行效率分析sql,对sql进行优化,当然建议并发执行取平均值作为参考数据

 

 

参考:

[官方]执行SQL分析打印

Mybatis-Plus--使用p6spy对SQL性能进行监控

SpringBoot 快速集成 p6spy 监控 SQL 性能,Mybaties-plus

MyBatis-Plus 高级功能 —— SQL性能分析打印插件