MyBatis-Plus 执行SQL分析打印
可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
使用步骤
1、p6spy 依赖引入
2、application.yml 配置
3、spy.properties 配置
- p6spy 依赖引入
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
- application.yml 配置
配置方法
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:h2:mem:test
...
注意: driver-class-name 为 p6spy 提供的驱动类
url 前缀为 jdbc:p6spy 跟着冒号为对应数据库连接地址
实际配置
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatisplus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 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
效果图
Mybatis-Plus 性能分析插件
注意:PerformanceInterceptor在3.2.0被移除了,如果想进行性能分析,用第三方的,官方这样写的“该插件
3.2.0
以上版本移除推荐使用第三方扩展执行SQL分析打印
功能”。虽然 Mybatis-Plus 性能分析插件 在 3.2.0 被移除了,还是可以学习、研究一下
Mybatis-Plus 内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
作用:我们平时开发中会遇到一些慢SQL。
使用性能分析拦截器,用于输出每条SQL语句以及其执行时间。
Mybatis-Plus也提供性能分析插件,如果超过这个时间就会停止运行。
使用步骤
1、导入插件
/**
* @Author LMGD
* @Date 2021/12/17 14:34
*/
@MapperScan("com.lmgd.mybatisplus.mapper")
@EnableTransactionManagement//添加事务
@Configuration
public class MyBatisPlusConfig {
/**
* sql执行效率插件
*/
@Bean
@Profile({"dev", "test"})
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
// 在工作中,不允许用户等待太久
performanceInterceptor.setMaxTime(100); // ms(单位毫秒) 设置sql执行的最大时间,如果超过了则不执行
performanceInterceptor.setFormat(true); // 是否进行格式化
return new PerformanceInterceptor();
}
}
注意:要在SpringBoot中配置环境为 dev 或 test 环境 !!!
spring.profiles.active=dev
# spring.profiles.active=test
2、测试使用