一、MP性能分析
1、添加攔截器
可以使用@Profile({"test", "dev"})來表明只在spring.profiles.active配置的環境下才去攔截。注意:性能分析有性能損耗,不建議在生產環境下開啟。
@Bean //@Profile({"test", "dev"}) public PerformanceInterceptor performanceInterceptor() { PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor(); performanceInterceptor.setFormat(true);//格式化SQL performanceInterceptor.setMaxTime(5L);//只對執行時間超出5毫秒的SQL進行攔截 return performanceInterceptor; }
2、測試
執行任意SQL,效果如下
二、執行 SQL 分析打印
該功能依賴 p6spy 組件,完美的輸出打印 SQL 及執行時長 3.1.0 以上版本
1、添加依賴
<dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.8.2</version> </dependency>
2、修改 application.yml 配置
spring:
datasource:
#driver-class-name: com.mysql.cj.jdbc.Driver
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
#url: jdbc:mysql://localhost:3306/mp?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
url: jdbc:p6spy:mysql://localhost:3306/mp?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
username: root
password: 123456
3、resources 目錄下增加 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
4、測試
提示:使用這種方式分析SQL,不需要注入上面的PerformanceInterceptor。