【Mybatis-Plus进阶学习(五)】性能分析插件

性能分析的简单使用

第一步:配置性能分析拦截器

    @Bean
    @Profile({"dev", "test"})//只用于开发和测试环境,不建议在生产环境使用
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        return performanceInterceptor;
    }

一般性能分析只用于开发和测试环境,不建议在生产环境使用。因为性能分析可以帮助发现一些问题,但是也是对资源的一种消耗。

第二步:配置环境

在VM options输入如下参数即可。

-Dspring.profiles.active=dev

运行即可看见,在输出结果的下方,有红色字体的性能分析结果。

第三步:配置性能分析参数

  • 输出格式化
performanceInterceptor.setFormat(true);


可以观察到性能分析结果被格式化。

  • 最大执行时间
        performanceInterceptor.setMaxTime(5L);

设置了5ms的最大执行时间,当SQL的执行时间超过了设定值,就会报错,如下:

执行Sql分析打印

该功能依赖 p6spy 组件,完美的输出打印 SQL 及执行时长 3.1.0 以上版本

第一步:引入依赖

        <dependency>
            <groupId>p6spy</groupId>
            <artifactId>p6spy</artifactId>
            <version>3.8.2</version>
        </dependency>

第二步:修改application.properties,使用 p6spy 启动数据库

spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatis_plus_test?useSSL=false&serverTimezone=GMT%2B8

第三步:添加spy.properties 配置

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
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
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

这里注意根据自己MybatisPlus的版本选择modulelist。

第四步:运行

结果如下

p6spy还有很多强大的功能,这里就不细说了。

原文地址:https://www.cnblogs.com/zllk/p/14239806.html